def CheckBlock(filename, curve):
    if os.path.isfile(filename):
        f = open(filename, "r")
        block = f.readlines()
        if len(block)%9 != 0:
            print("Incorrect file format")
            f.close()
            return -10000
        block_count = len(block)//9
        for i in range(0, block_count):
            # coordinates of the public key point
            x1 = int(block[i*9+2][22:-1])
            y1 = int(block[i*9+3][22:-1])
            r = int(block[i*9+7][15:-1])
            s = int(block[i*9+8][15:-1])
            tx = "".join(block[i*9: i*9+7])
            # For the signature verfication
            payer = ECDSA()
            payer_pk = ECPublicKey(Point(x1, y1, curve))
            signature = encode_sig(r, s)
            try:
                assert(payer.verify(tx.encode('UTF-8'), signature, payer_pk))
                ver = 0
                f.close()
                return ver
            except:
                ver = -i-1
                f.close()
                return ver
        return 0
    else:
        print("File does not exist")
        return -10000
예제 #2
0
파일: main.py 프로젝트: ionagamed/iu-dlt-04
def _():
    cv = Curve.get_curve('secp256k1'); pu_key = ECPublicKey(
        Point(0x65d5b8bf9ab1801c9f168d4815994ad35f1dcb6ae6c7a1a303966b677b813b00,
              0xe6b865e529b8ecbf71cf966e900477d49ced5846d7662dd2dd11ccd55c0aff7f,
              cv))
    pv_key = ECPrivateKey(
        0xfb26a4e75eec75544c0f44e937dcf5ee6355c7176600b9688c667e5c283b43c5,
        cv) ; signer = ECDSA(fmt="ITUPLE")
    sig = signer.sign(b'01234567890123456789012345678912', pv_key) ;return sig
예제 #3
0
def getSignData(original_data, pk):

    json_str = json.dumps(original_data).replace(' ', '')
    byte_str = json_str.encode()
    sha256 = SHA256Hash(byte_str)
    byte_str_hash = sha256.digest()  # 返回byte类型哈希
    # 私钥签名
    signer = ECDSA()
    raw_sig = signer.sign(byte_str_hash, pk)  # sign返回的byte对象
    hex_sig = ByteToHex(raw_sig).lower()  # 将签名后byte转为hex,并修改字母为小写
    return hex_sig
    def __verifyUsingPublicKey(self, signature, api_key, params, timestamp,
                               public_key):
        signer = ECDSA()
        pu_bytes = base64.b64decode(public_key)
        # int(pu_bytes[1:33].encode('hex'), 16)
        x = int(binascii.hexlify(pu_bytes[1:33]), 16)
        y = int(binascii.hexlify(pu_bytes[33:]), 16)
        pu_key = ECPublicKey(Point(x, y, cv))
        hashed = hashlib.sha256("{}.{}.{}".format(
            api_key, params, timestamp).encode("UTF-8")).hexdigest()

        return signer.verify(bytearray.fromhex(hashed),
                             bytearray.fromhex(signature), pu_key)
예제 #5
0
def gen_random_tx(curve):
    n = curve.order
    P = curve.generator
    sA = random.randint(0, n)
    sk = ECPrivateKey(sA, curve)
    QA = sA * P
    pk = ECPublicKey(QA)

    payee_sA = random.randint(0, n)
    payee_sk = ECPrivateKey(payee_sA, curve)
    payee_QA = sA * P
    payee_pk = ECPublicKey(payee_QA)

    sum_string = "*** Bitcoin transaction ***\n"

    serial = random.getrandbits(128)
    sum_string += "Serial number: " + str(serial) + "\n"

    sum_string += "Payer Public key - x: " + str(QA.x) + "\n"

    sum_string += "Payer Public key - y: " + str(QA.y) + "\n"

    sum_string += "Payee Public key - x: " + str(payee_QA.x) + "\n"

    sum_string += "Payee Public key - y: " + str(payee_QA.y) + "\n"

    amount = random.randint(1, 1000000)
    sum_string += "Amount: " + str(amount) + " Satoshi" + "\n"

    signer = ECDSA()

    sig = signer.sign(sum_string.encode('UTF-8'), sk)

    (r, s) = decode_sig(sig)

    # k = random.randint(1, n - 1)
    # R = k * P
    # r = R.x % n
    # #r = str(r).encode('UTF-8')
    # h = hashlib.sha3_256()
    # h.update(sum_string.encode('UTF-8'))
    # # h.update(str(r).encode('UTF-8'))
    # #h.update(r)  # m + r
    # s = (modinv(k, n) * ((int(h.hexdigest(), 16)) + (sA * r))) % n
    # #h = int(h.hexdigest(), 16)

    sum_string += "Signature - r: " + str(r) + "\n"

    sum_string += "Signature - s: " + str(s) + "\n"

    return sum_string
    def generate_signature(self, private_key):
        """
        :return: {Message}SK, where Message = contents of TxIn and TxOut and Transaction ID
        """
        txin = self.tx_Ins[-1]
        txout = self.tx_Outs[-1]
        tx_in_str = txin.get_tx_in_content()
        tx_out_str = txout.get_tx_out_content()
        tran_id = self.get_transaction_id()
        message = tx_in_str + tx_out_str + tran_id

        signer = ECDSA()
        sig = signer.sign(message.encode('utf-8'), private_key)
        txin.signature = sig
        return sig
예제 #7
0
def verify(api_key, api_secret, params, signature, timestamp):
    payload = __composePayload(api_key, params, timestamp)
    pv_key = ECPrivateKey(
        int(binascii.hexlify(base64.b64decode(api_secret)), 16), cv)
    hashed_payload = hashlib.sha256(payload.encode("UTF-8")).hexdigest()

    return ECDSA().verify(bytearray.fromhex(hashed_payload),
                          bytearray.fromhex(signature),
                          pv_key.get_public_key())
예제 #8
0
def gen_random_tx(curve):
    # get a random 128 BIT integer for serial number
    serial_num = Num.getRandomNBitInteger(128)

    # create the public key for sender
    n = curve.order
    P = curve.generator
    sA = Num.getRandomRange(0, n + 1)
    sK = ECPrivateKey(sA, curve)
    QA = sA * P
    pk = ECPublicKey(QA)

    signer = ECDSA()

    # create the public key for sendee
    sA_2 = Num.getRandomRange(0, n + 1)
    sK_2 = ECPrivateKey(sA_2, curve)
    P2 = curve.generator
    QA_2 = sA_2 * P2
    pk_2 = ECPublicKey(QA_2)

    # header for the block
    temp = "*** Bitcoin transaction ***\n"

    # add the serial number to the block
    temp = temp + "Serial number: " + str(serial_num) + "\n"
    # write payers public keys
    temp = temp + "Payer public key - x: " + str(QA.x) + "\n"
    temp = temp + "Payer public key - y: " + str(QA.y) + "\n"
    # write payees public keys
    temp = temp + "Payee public key - x: " + str(QA_2.x) + "\n"
    temp = temp + "Payee public key - y: " + str(QA_2.y) + "\n"

    # get random transaction val
    amount = Num.getRandomRange(0, 1000001)
    temp = temp + "Amount: " + str(amount) + "\n"

    sig = signer.sign(temp.encode("utf-8"), sK)
    (r, s) = decode_sig(sig)
    temp = temp + "Signature (r): " + str(r) + "\n"
    temp = temp + "Signature (s): " + str(s) + "\n"

    return temp
예제 #9
0
def sign(api_key, api_secret, params, timestamp=None):
    if timestamp is None:
        timestamp = __currentTimestamp()
    payload = __composePayload(api_key, params, timestamp)
    hashed_payload = hashlib.sha256(payload.encode("UTF-8")).hexdigest()

    pv_key = ECPrivateKey(
        int(binascii.hexlify(base64.b64decode(api_secret)), 16), cv)
    signature_bytes = ECDSA().sign(bytearray.fromhex(hashed_payload), pv_key)
    return binascii.hexlify(signature_bytes).decode("UTF-8"), timestamp
def gen_random_tx(curve):
    serial = random.randint(0,
                            2**128 - 1)  # creates 128 bit random serial number
    n = curve.order
    P = curve.generator
    sA = random.randint(0, n)
    sk = ECPrivateKey(sA, curve)
    QA = sA * P
    pk = ECPublicKey(QA)

    sB = random.randint(0, n)
    skB = ECPrivateKey(sB, curve)
    QB = sB * P
    pkB = ECPublicKey(QB)

    amount = random.randint(1, 1000000)  # create a random int for amount

    transaction = "**** Bitcoin transaction ****\n"
    transaction += "Serial number: " + str(serial) + "\n"
    transaction += "Payer public key - x: " + str(QA.x) + "\n"
    transaction += "Payer public key - y: " + str(QA.y) + "\n"
    transaction += "Payee public key - x: " + str(QB.x) + "\n"
    transaction += "Payee public key - y: " + str(QB.y) + "\n"
    transaction += "Amount: " + str(amount) + "\n"

    signer = ECDSA()

    message = transaction
    message = message.encode('UTF-8')
    sig = signer.sign(message, sk)

    (r, s) = decode_sig(sig)

    transaction += "Signature (r): " + str(r) + "\n"
    transaction += "Signature (s): " + str(s) + "\n"
    return transaction
예제 #11
0
def gen_random_tx(curve):
    serial = random.randrange(pow(2, 127), pow(2, 128))
    amount = random.randrange(1, 1000001)

    n = curve.order
    P = curve.generator

    sA = random.randint(0, n)
    sB = random.randint(0, n)

    skA = ECPrivateKey(sA, curve)
    skB = ECPrivateKey(sB, curve)
    QA = sA * P
    QB = sB * P

    pkA = ECPublicKey(QA)
    pkB = ECPublicKey(QB)

    signer = ECDSA()

    trans = "**** Bitcoin transaction ****" + \
        "\nSerial number: " + str(serial) + \
        "\nPayer public key - x: " + str(QA.x) + \
        "\nPayer public key - y: " + str(QA.y) + \
        "\nPayee public key - x: " + str(QB.x) + \
        "\nPayee public key - y: " + str(QB.y) + \
        "\nAmount: " + str(amount) + "\n"
    t = trans.encode("UTF-8")
    sig = signer.sign(t, skA)

    (r, s) = decode_sig(sig)

    trans += "Signature (r): " + str(r) + "\n" + "Signature (s): " + str(
        s) + "\n"

    return trans
예제 #12
0
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

from Crypto.Random import random

from binascii import hexlify, unhexlify
import time
import json

from ecpy.curves import curve_secp256k1
from ecpy.point import Point, Generator
from ecpy.ecdsa import ECDSA

_def_curve = curve_secp256k1
Point.set_curve(_def_curve)
ECDSA.set_curve(_def_curve)
ECDSA.set_generator(Generator.init(_def_curve['G'][0], _def_curve['G'][1]))

class NAK(object):
    n = _def_curve['n']
    G = Generator.init(_def_curve['G'][0], _def_curve['G'][1])
    ecdsa = ECDSA()
    
    def __init__(self, expire=None, pubkey=None, signature=None, privkey=None):
        self.expire = expire
        self.pubkey = pubkey
        self.signature = signature
        self.privkey = privkey
        if privkey is not None and pubkey is None:
            self.pubkey = NAK.G * privkey
        if self.pubkey is not None:
예제 #13
0
class NAK(object):
    n = _def_curve['n']
    G = Generator.init(_def_curve['G'][0], _def_curve['G'][1])
    ecdsa = ECDSA()
    
    def __init__(self, expire=None, pubkey=None, signature=None, privkey=None):
        self.expire = expire
        self.pubkey = pubkey
        self.signature = signature
        self.privkey = privkey
        if privkey is not None and pubkey is None:
            self.pubkey = NAK.G * privkey
        if self.pubkey is not None:
            self.pubkeyb = unhexlify(self.pubkey.compress())
        else:
            self.pubkeyb = None

    @staticmethod
    def deserialize(rawbytes):
        etime = int(hexlify(rawbytes[0:4]), 16)
        #print('time = ' + str(time.gmtime(etime)))
        Pkey = Point.decompress(hexlify(rawbytes[4:37]))
        #print('point = ' + Pkey.compress())
        sig0 = int(hexlify(rawbytes[37:69]),16)
        sig1 = int(hexlify(rawbytes[69:101]),16)
        sig = (sig0, sig1)
        #print('sig = (0x%032x, 0x%032x)' % (sig[0], sig[1]))
        #print('verifying %s' % hexlify(rawbytes[:37]))
        if not NAK.ecdsa.verify(Pkey,sig,rawbytes[:37]):
            #print('verify failed')
            return None
        return NAK(etime, Pkey, sig)

    def serialize(self):
        hexmsg = b'%08x' % self.expire
        hexmsg += self.pubkey.compress()
        if self.signature is None:
            if self.privkey is None:
                return None
            else:
                bmsg = unhexlify(hexmsg)
                self.signature = NAK.ecdsa.sign(self.privkey, bmsg)
        hexmsg += b'%064x' % self.signature[0]
        hexmsg += b'%064x' % self.signature[1]
        return unhexlify(hexmsg)

    def randomize(self, expire=None):
        self.privkey = random.randint(1,NAK.n-1)
        self.pubkey = NAK.G * self.privkey
        if expire is not None:
            self.expire = expire
        else:
            self.expire = int(time.time()) + (365*24*60*60)
        self.serialize()

    def dumpjson(self):
        exp = {}
        if self.signature is None:
            serialized = self.serialize()
            if serialized is None:
                return None
        exp['pubkey'] = self.pubkey.compress().decode()
        exp['expire'] = self.expire
        exp['signature'] = self.signature
        return json.dumps(exp)

    @staticmethod
    def loadjson(load):
        try:
            raw = json.loads(load)
            expire = raw['expire']
            pubkey = Point.decompress(raw['pubkey'])
            signature = raw['signature']
            return NAK(expire, pubkey, signature)
        except:
            return None

    def sign(self,message):
        if self.privkey is None:
            return None
        return NAK.ecdsa.sign(self.privkey, message)

    def verify(self,signature,message):
        if self.pubkey is None:
            return False
        return NAK.ecdsa.verify(self.pubkey, signature, message)

    def pubkeybin(self):
        if self.pubkeyb is not None:
            return self.pubkeyb
        if self.pubkey is not None:
            self.pubkeyb = unhexlify(self.pubkey.compress())
            return self.pubkeyb
        return None

    def __eq__(self, r):
        if self.expire != r.expire:
            return False
        if self.pubkey != r.pubkey:
            return False
        return True

    def __ne__(self, r):
        return not (self == r)

    def __gt__(self, r):
        if self.expire == r.expire:
            return self.pubkey.compress() > r.pubkey.compress()
        return self.expire > r.expire

    def __lt__(self, r):
        if self.expire == r.expire:
            return self.pubkey.compress() < r.pubkey.compress()
        return self.expire < r.expire

    def __le__(self, r):
        return not (self > r)

    def __ge__(self, r):
        return not (self < r)
    
    def __str__(self):
        return str(self.pubkey) + ' expires ' + str(time.gmtime(self.expire))
    
    def __repr__(self):
        ser = self.serialize()
        if ser is not None:
            return 'NAK.deserialize(unhexlify(%s))' % hexlify(ser)
        return 'NAK(0x%08x,Point.decompress(%s))' % (self.expire, self.pubkey.compress())
예제 #14
0
from ecpy.formatters import decode_sig, encode_sig

if sys.version_info < (3, 6):
    import sha3

# You can keep this part (i.e., curve setting and key generation)
curve = Curve.get_curve('secp256k1')
n = curve.order
P = curve.generator
sA = random.randint(0, n)
sk = ECPrivateKey(sA, curve)
QA = sA * P
pk = ECPublicKey(QA)

# You need to change sign and verify methods below
signer = ECDSA()  # this line can be removed
message = b'Anything goes here'
sig = signer.sign(message, sk)  # new sign method here

verifier = ECDSA()  # this line can be removed

message = b'Anything goes here'
try:
    assert (verifier.verify(message, sig, pk))  # new sign method here
    print("Signature verifies")
except:
    print("Signature does not verify")

message = b'Anything goes heree'
try:
    assert (verifier.verify(message, sig, pk))  # new sign method here
예제 #15
0
import base64
import json
import sys
from binascii import hexlify, unhexlify
import nak

from ecpy.curves import curve_secp256k1
from ecpy.point import Point, Generator
from ecpy.ecdsa import ECDSA
from Crypto.Random import random
from Crypto.Cipher import AES
from Crypto.Util import Counter

Point.set_curve(curve_secp256k1)
_G = Generator.init(curve_secp256k1['G'][0], curve_secp256k1['G'][1])
ECDSA.set_generator(_G)

client_p = random.randint(1,curve_secp256k1['n']-1)
client_P = _G * client_p

client_r = random.randint(1,curve_secp256k1['n']-1)
client_R = _G * client_r

ecdsa=ECDSA()

_server = "http://indigo.bounceme.net:5000/"
_server2 = "http://coopr8.com:5000/"
_server3 = "http://ciphrtxt.com:5000/"
_status = "api/status/"
_onion = "onion/"
_nak_priv = 0xf1a91fc566427a45cd6cdd43f5fc5647b1d6696a5b03f868b9bb8b01b631ae91
예제 #16
0
import hashlib
import base64
import json
from binascii import hexlify, unhexlify

from ecpy.curves import curve_secp256k1
from ecpy.point import Point, Generator
from ecpy.ecdsa import ECDSA
from Crypto.Random import random
from Crypto.Cipher import AES
from Crypto.Util import Counter

_curve = curve_secp256k1
Point.set_curve(_curve)
_G = Generator.init(_curve['G'][0], _curve['G'][1])
ECDSA.set_generator(_G)

server_p = random.randint(1, curve_secp256k1['n'] - 1)
server_P = _G * server_p

config = {}
config['receive_dir'] = "recv/"
config['message_dir'] = "messages/"
config['capacity'] = (128 * 1024 * 1024 * 1024)
config['max_file_size'] = (256 * 1024 * 1024)
config['ncache_sleep_interval'] = 30
config['version'] = '0.0.2'

clopts = []
clopts.append({'name': 'rpcuser', 'default': None})
clopts.append({'name': 'rpcpass', 'default': None})
예제 #17
0
import hashlib
import base64
import json
from binascii import hexlify, unhexlify

from ecpy.curves import curve_secp256k1
from ecpy.point import Point, Generator
from ecpy.ecdsa import ECDSA
from Crypto.Random import random
from Crypto.Cipher import AES
from Crypto.Util import Counter

_curve = curve_secp256k1
Point.set_curve(_curve)
_G = Generator.init(_curve['G'][0], _curve['G'][1])
ECDSA.set_generator(_G)

server_p = random.randint(1,curve_secp256k1['n']-1)
server_P = _G * server_p

config={}
config['receive_dir'] = "recv/"
config['message_dir'] = "messages/"
config['capacity'] = (128*1024*1024*1024)
config['max_file_size'] = (256*1024*1024)
config['ncache_sleep_interval'] = 30
config['version'] = '0.0.2'

clopts = []
clopts.append({'name':'rpcuser', 'default':None})
clopts.append({'name':'rpcpass', 'default':None})
def P2PKH(private_key, tran, txin, txout):
    """
    :param tran: <Transaction> object
    :param txin: <TxIn> object
    :param txout: <TxOut> object
    :return: <Bool> True or False
    """
    stack = []

    # get signature and add it to stack
    signature = tran.generate_signature(private_key)
    stack.append(signature)  # stack[0]

    # get public key and add it to stack
    public_key = txin.public_key
    stack.append(public_key)  # stack[1]

    # copy the public key and add the copy to stack
    public_key_copy = copy.deepcopy(str(public_key))
    stack.append(public_key_copy)  # stack[2]

    # apply hash function to copy of public key
    hash_public_key_copy = sha256(public_key_copy.encode('utf-8')).hexdigest()
    stack[2] = hash_public_key_copy  # stack[2]

    # get address of recipient and add it to stack
    hash_public_key = txout.address
    stack.append(hash_public_key)  # stack[3]

    print('\n################# stack 1 #####################')
    pprint(stack)

    # check if address matches the hash value of public key
    if stack[2] == stack[3]:
        stack.pop(3)
        stack.pop(2)
        print('\naddress match')
    else:
        print('\naddress does not match')
        return False

    print('\n################# stack 2 #####################')
    pprint(stack)

    # get whole transaction messages except the signature
    tx_in_str = txin.get_tx_in_content()
    tx_out_str = txout.get_tx_out_content()
    tran_id = tran.get_transaction_id()
    message = tx_in_str + tx_out_str + tran_id

    # Instantiate a signer
    signer = ECDSA()

    # check the integrity of message, i.e. M = S{PU} = {{M}PK}PU = M
    valid = signer.verify(str(message).encode('utf-8'), stack[0], stack[1])
    if valid:
        stack.pop(1)
        stack.pop(0)
        print('\nsignature is valid')
    else:
        print('\nsignature is not valid')
        return False

    print('\n################# stack 3 #####################')
    pprint(stack)

    # if the stack is empty, then the transaction is said to be verified
    if not stack:
        print('\nTransaction verified')
        return True
    else:
        print('\nTransaction not verified')
        return False
예제 #19
0
import hashlib
try:
    import secp256k1
    USE_SECP = secp256k1.HAS_ECDH
except (ImportError, AttributeError):
    USE_SECP = False

if not USE_SECP:
    import ecpy
    from builtins import int
    from ecpy.curves import Curve, Point
    from ecpy.keys import ECPublicKey, ECPrivateKey
    from ecpy.ecdsa import ECDSA
    CURVE_SECP256K1 = Curve.get_curve('secp256k1')
    SIGNER = ECDSA()


class PublicKey(object):
    def __init__(self, pubkey=None, raw=False, flags=None, ctx=None):
        if USE_SECP:
            if flags == None:
                flags = secp256k1.FLAG_VERIFY
            self.obj = secp256k1.PublicKey(pubkey, raw, flags, ctx)
        else:
            if not raw:
                raise Exception("Non raw init unsupported")
            pubkey = pubkey[1:]
            x = int.from_bytes(pubkey[0:32], 'big')
            y = int.from_bytes(pubkey[32:], 'big')
            self.obj = ECPublicKey(Point(x, y, CURVE_SECP256K1))
예제 #20
0
 def generate_key(self, curve):  # curve : curve 이름
     cv = Curve.get_curve(curve)
     pv_key = ECPrivateKey(rnd(cv.order), cv)
     pu_key = pv_key.get_public_key()
     return (pu_key, pv_key, cv, ECDSA())
예제 #21
0
import ecpy.curves as curves
from ecpy.ecdsa import ECDSA
from Crypto.Random import random
from Crypto.Cipher import AES
from Crypto.Util import Counter
import hashlib
import binascii
import base64

#_curve = curves.curve_secp112r1
_curve = curves.curve_secp256k1
#_curve = curves.curve_secp384r1

Point.set_curve(_curve)
_G = Generator.init(_curve['G'][0], _curve['G'][1])
ECDSA.set_curve(_curve)
ECDSA.set_generator(_G)

ecdsa = ECDSA()
recdsa = ECDSA()

friends = ['Alice', 'Bob', 'Carl', 'Donna', 'Eve']

data = []
for f in friends:
    datum = {}
    datum['name'] = f
    p = random.randint(1,_curve['n']-1)
    P = p * _G
    datum['privkey'] = p
    datum['pubkey'] = P
예제 #22
0
from ecpy.ecdsa import ECDSA

# version = 1.00 in fixed point
_msg_api_ver_v1 = b'M0100'
_msg_api_ver_v2 = b'M\x02\x00\x00'

_C = curve_secp256k1
# _C = curve_secp384r1
# _C = curve_secp112r1
# _C = curve_bauer9

_masksize = min(32, _C['bits'])
_maskbits = (int((_masksize / 3) + 0))

_G = Generator.init(_C['G'][0], _C['G'][1])
ECDSA.set_curve(_C)
ECDSA.set_generator(_G)
_ecdsa = ECDSA()

# convert integer to hex string
_pfmt = '%%0%dx' % (((_C['bits'] + 7) >> 3) << 1)
_mfmt = '%%0%dx' % (((_masksize + 7) >> 3) << 1)

# 256 bit message seed
_s_bytes = 32 
# 64 bit plaintext length field
_l_bytes = 8

_lfmt = '%016x'

_header_size_v1 = (5+1+8+1+8+1+66+1+66+1+66)
예제 #23
0
from ecpy.keys import ECPublicKey, ECPrivateKey
from ecpy.ecdsa import ECDSA
from ecpy.formatters import decode_sig, encode_sig

if sys.version_info < (3, 6):
    import sha3

curve = Curve.get_curve('secp256k1')
n = curve.order
P = curve.generator
sA = random.randint(0,n)
sk = ECPrivateKey(sA, curve)
QA = sA*P
pk = ECPublicKey(QA)

signer = ECDSA()

message = b'Anything goes here'

sig = signer.sign(message, sk)

(r, s) = decode_sig(sig)

f = open("deneme.txt", "w")
f.write("Public key - x: " + str(QA.x)+"\n")
f.write("Public key - y: " + str(QA.y)+"\n")
f.write("Signature - r: " + str(r)+"\n")
f.write("Signature - s: " + str(s)+"\n")
f.close()

f = open("deneme.txt", "r")
예제 #24
0
from ecpy.curves import Curve, Point
from ecpy.keys import ECPublicKey, ECPrivateKey
from ecpy.ecdsa import ECDSA
import hashlib
import binascii
import settings

# blind signature
cv = Curve.get_curve('secp256k1')
signer = ECDSA()
pv_key = ECPrivateKey(
    int(hashlib.md5(settings.PRIVATE_KEY.encode()).hexdigest(), 16), cv)
pu_key = pv_key.get_public_key()
d = pv_key.d
P = pu_key.W
n = cv.order
G = cv.generator
r = 1
R = r * G
hasher = hashlib.sha256()


def int_to_bytes(x):
    return x.to_bytes((x.bit_length() + 7) // 8, byteorder='big')


def hex_to_bytes(x):
    x = int(x, 16)
    return int_to_bytes(x)

예제 #25
0
from hashlib import sha256
from typing import Callable, Tuple, Type, cast

from ecpy.curves import Curve  # type: ignore
from ecpy.ecdsa import ECDSA  # type: ignore
from ecpy.keys import ECPrivateKey, ECPublicKey  # type: ignore
from typing_extensions import Final, Literal

from xrpl.core.keypairs.crypto_implementation import CryptoImplementation
from xrpl.core.keypairs.exceptions import XRPLKeypairsException
from xrpl.core.keypairs.helpers import sha512_first_half

_CURVE: Final[Curve] = Curve.get_curve("secp256k1")
_GROUP_ORDER: Final[int] = _CURVE.order
_SIGNER: Final[ECDSA] = ECDSA("DER")

# String keys must be _KEY_LENGTH long
_KEY_LENGTH: Final[int] = 66
# Pad string keys with _PADDING_PREFIX to reach _KEY_LENGTH
_PADDING_PREFIX: Final[str] = "0"

# Generated sequence values are _SEQUENCE_SIZE bytes unsigned big-endian
_SEQUENCE_SIZE: Final[int] = 4
_SEQUENCE_MAX: Final[int] = 256**_SEQUENCE_SIZE

# Intermediate private keys are always padded with 4 bytes of zeros
_INTERMEDIATE_KEYPAIR_PADDING: Final[bytes] = (0).to_bytes(
    4,
    byteorder="big",
    signed=False,
예제 #26
0
 def generate_key_with_peerid(self, curve, peerid):
     cv = Curve.get_curve(curve)
     pv_key = ECPrivateKey(peerid, cv)
     pu_key = pv_key.get_public_key()
     return (pu_key, pv_key, cv, ECDSA())
예제 #27
0
파일: ecdsa.py 프로젝트: lochotzke/ECPy
### ECS
# test key
cv     = Curve.get_curve('secp256k1')
pv_key = ECPrivateKey(0xf028458b39af92fea938486ecc49562d0e7731b53d9b25e2701183e4f2adc991,cv)
pu_key = ECPublicKey(Point(0x81bc1f9486564d3d57a305e8f9067df2a7e1f007d4af4fed085aca139c6b9c7a,
                           0x8e3f35e4d7fb27a56a3f35d34c8c2b27cd1d266d5294df131bf3c1cbc39f5a91,
                           cv))


k = pv_key.get_public_key()
assert(k.W.x == pu_key.W.x)
assert(k.W.y == pu_key.W.y)

print("Public key ok")

msg = 0x8c7632afe967e2e16ae7f39dc32c252b3d751fa6e01daa0efc3c174e230f4617
msg = msg.to_bytes(32,'big')

sig = 0x304402203a329589dbc6f3bb88bf90b45b5d4935a18e13e2cb8fcee0b94b3102ec19645702202f61af55df0e56e71d40a9f5f111faeb2f831c1fd314c55227ac44110fb33049
sig = sig.to_bytes(70,'big')

## verify
signer = ECDSA()

while True:
    sig = signer.sign(msg,pv_key)
    signer.verify(msg,sig,pu_key)

assert(signer.verify(msg,sig,pu_key))        
예제 #28
0
import base64
import json
import sys
from binascii import hexlify, unhexlify
import nak

from ecpy.curves import curve_secp256k1
from ecpy.point import Point, Generator
from ecpy.ecdsa import ECDSA
from Crypto.Random import random
from Crypto.Cipher import AES
from Crypto.Util import Counter

Point.set_curve(curve_secp256k1)
_G = Generator.init(curve_secp256k1['G'][0], curve_secp256k1['G'][1])
ECDSA.set_generator(_G)

client_p = random.randint(1, curve_secp256k1['n'] - 1)
client_P = _G * client_p

client_r = random.randint(1, curve_secp256k1['n'] - 1)
client_R = _G * client_r

ecdsa = ECDSA()

_server = "http://indigo.bounceme.net:5000/"
_server2 = "http://coopr8.com:5000/"
_server3 = "http://ciphrtxt.com:5000/"
_status = "api/status/"
_onion = "onion/"
_nak_priv = 0xf1a91fc566427a45cd6cdd43f5fc5647b1d6696a5b03f868b9bb8b01b631ae91