Python ecdsa.VerifyingKey.from_string() Examples

The following are 19 code examples of ecdsa.VerifyingKey.from_string(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ecdsa.VerifyingKey , or try the search function .
Example #1
Source File: hd_public_key.py    From ontology-python-sdk with GNU Lesser General Public License v3.0 6 votes vote down vote up
def from_parent(parent_key, i):
        if i & HARDENED_INDEX:
            raise ValueError("Can't generate a hardened child key from a parent public key.")

        child = hmac.new(parent_key.chain_code,
                         parent_key.compressed_key + i.to_bytes(length=4, byteorder='big'),
                         hashlib.sha512).digest()
        child_left, child_right = child[:32], child[32:]
        if int.from_bytes(child_left, 'big') >= ecdsa.generator_256.order():
            return None

        temp_pri_key = SigningKey.from_string(string=child_left, curve=curves.NIST256p)

        ki = temp_pri_key.verifying_key.pubkey.point + parent_key.key.pubkey.point
        if ki == ellipticcurve.INFINITY:
            return None

        return HDPublicKey(public_key=VerifyingKey.from_public_point(point=ki, curve=curves.NIST256p),
                           chain_code=child_right,
                           index=i,
                           depth=parent_key.depth + 1,
                           parent_fingerprint=parent_key.fingerprint) 
Example #2
Source File: transaction.py    From Foundations-of-Blockchain with MIT License 6 votes vote down vote up
def sign_tx_in(transaction, tx_in_index,
               private_key, a_unspent_tx_outs):

    tx_in = transaction.tx_ins[tx_in_index]
    data_to_sign = str(transaction.id)
    referenced_utxo = find_unspent_tx_out(tx_in.tx_out_id, tx_in.tx_out_index, a_unspent_tx_outs)
    if referenced_utxo is None:
        print('could not find referenced txOut')
        # throw Error()
        return False

    referenced_address = referenced_utxo.address

    if get_public_key(private_key) != referenced_address:
        print('trying to sign an input with private' +
              ' key that does not match the address that is referenced in tx_in')
        # throw Error()
        return False

    # key = ec.keyFromPrivate(private_key, 'hex')
    sk = SigningKey.from_string(private_key, curve=SECP256k1)
    signature = binascii.b2a_hex(sk.sign(data_to_sign.encode())).decode()
    return signature 
Example #3
Source File: transaction.py    From Foundations-of-Blockchain with MIT License 6 votes vote down vote up
def validate_tx_in(tx_in, transaction, a_unspent_tx_outs):

    referenced_utxo = [utxo for utxo in a_unspent_tx_outs if utxo.tx_out_id == tx_in.tx_out_id and utxo.tx_out_index == tx_in.tx_out_index][0]
    if referenced_utxo == []:
        print('referenced txOut not found: ' + json.dumps(tx_in))
        return False

    address = referenced_utxo.address

    vk = VerifyingKey.from_string(bytes.fromhex(address), curve=SECP256k1)

    try:
        vk.verify(bytes.fromhex(tx_in.signature), transaction.id.encode())

    except Exception as e:
        # change the exception
        print('invalid tx_in signature: %s txId: %s address: %s' % (tx_in.signature, transaction.id, referenced_utxo.address))
        return False

    return True 
Example #4
Source File: client.py    From HWI with MIT License 6 votes vote down vote up
def mitm_verify(self, sig, expected_xpub):
        # First try with Pycoin
        try:
            from pycoin.key.BIP32Node import BIP32Node
            from pycoin.contrib.msg_signing import verify_message
            from pycoin.encoding  import from_bytes_32
            from base64 import b64encode

            mk = BIP32Node.from_wallet_key(expected_xpub)
            return verify_message(mk, b64encode(sig), msg_hash=from_bytes_32(self.session_key))
        except ImportError:
            pass

        # If Pycoin is not available, do it using ecdsa
        from ecdsa import BadSignatureError, SECP256k1, VerifyingKey
        pubkey, chaincode = decode_xpub(expected_xpub)
        vk = VerifyingKey.from_string(get_pubkey_string(pubkey), curve=SECP256k1)
        try:
            ok = vk.verify_digest(sig[1:], self.session_key)
        except BadSignatureError:
            ok = False

        return ok 
Example #5
Source File: client.py    From HWI with MIT License 6 votes vote down vote up
def ec_mult(self, his_pubkey):
        # - second call: given the pubkey of far side, calculate the shared pt on curve
        # - creates session key based on that
        from ecdsa.curves import SECP256k1
        from ecdsa import VerifyingKey
        from ecdsa.util import number_to_string

        # Validate his pubkey a little: this call will check it's on the curve.
        assert len(his_pubkey) == 64
        his_pubkey = VerifyingKey.from_string(his_pubkey, curve=SECP256k1, hashfunc=sha256)

        #print("his pubkey = %s" % b2a_hex(his_pubkey.to_string()))

        # do the D-H thing
        pt = self.my_key.privkey.secret_multiplier * his_pubkey.pubkey.point

        # final key is sha256 of that point, serialized (64 bytes).
        order = SECP256k1.order
        kk = number_to_string(pt.x(), order) + number_to_string(pt.y(), order)

        del self.my_key

        return sha256(kk).digest() 
Example #6
Source File: keys.py    From bitcoin_tools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_compressed_pk(pk):
    """
    Constructs the compressed representation of a SECP256k1 ECDSA public key form a given uncompressed key.

    :param pk: The uncompressed SECP256k1 key to be decompressed.
    :type pk: hex
    :return: The compressed SECP256k1 ECDSA key.
    :rtype: hex
    """

    ecdsa_pk = VerifyingKey.from_string(unhexlify(pk[2:]), curve=SECP256k1)
    compressed_pk = serialize_pk(ecdsa_pk)

    return compressed_pk 
Example #7
Source File: bravecore.py    From evesrp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def hex2key(hex_key):
        key_bytes = unhexlify(hex_key)
        if len(hex_key) == 64:
            return SigningKey.from_string(key_bytes, curve=NIST256p,
                    hashfunc=sha256)
        elif len(hex_key) == 128:
            return VerifyingKey.from_string(key_bytes, curve=NIST256p,
                    hashfunc=sha256)
        else:
            raise ValueError("Key in hex form is of the wrong length.") 
Example #8
Source File: hd_public_key.py    From ontology-python-sdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def from_bytes(cls, data: bytes):
        """ Generates either a HDPublicKey from the underlying bytes.

        The serialization must conform to the description in:
        https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#serialization-format
        """
        if len(data) < 78:
            raise ValueError("b must be at least 78 bytes long.")

        version = int.from_bytes(data[:4], 'big')
        depth = data[4]
        parent_fingerprint = data[5:9]
        index = int.from_bytes(data[9:13], 'big')
        chain_code = data[13:45]
        key_bytes = data[45:78]

        if version != HDPublicKey.__VERSION:
            raise ValueError('invalid HD Public Key.')

        if key_bytes[0] != 0x02 and key_bytes[0] != 0x03:
            raise ValueError("First byte of public key must be 0x02 or 0x03!")

        # The curve of points satisfying y^2 = x^3 + a*x + b (mod p).
        curve = ecdsa.curve_256
        x = util.string_to_number(key_bytes[1:])
        y = (x * x * x + curve.a() * x + curve.b()) % curve.p()
        y = numbertheory.square_root_mod_prime(y, curve.p())
        if (key_bytes[0] == 0x03 and y % 2 == 0) or (key_bytes[0] == 0x02 and y % 2 != 0):
            y = (y * -1) % curve.p()
        order = curves.NIST256p.order
        s_key = util.number_to_string(x, order) + util.number_to_string(y, order)

        public_key = VerifyingKey.from_string(string=s_key, curve=curves.NIST256p)
        rv = cls(
            public_key=public_key,
            chain_code=chain_code,
            index=index,
            depth=depth,
            parent_fingerprint=parent_fingerprint)
        return rv 
Example #9
Source File: hd.py    From btcpy with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_child(self, index, hardened=False):
        left, right = self.get_hash(index, hardened)
        point = ((left * generator_secp256k1)
                 + VerifyingKey.from_string(self.key.uncompressed[1:], curve=SECP256k1).pubkey.point)
        if point == INFINITY:
            raise ValueError('Computed point equals INFINITY')
        return ExtendedPublicKey(PublicKey.from_point(point), right, self.depth+1, self.get_fingerprint(), index, False) 
Example #10
Source File: transaction.py    From Foundations-of-Blockchain with MIT License 5 votes vote down vote up
def get_public_key(private_key):

    sk = SigningKey.from_string(private_key
                                , curve=SECP256k1)
    vk = sk.get_verifying_key()
    return binascii.b2a_hex(vk.to_string()).decode() 
Example #11
Source File: digital_signature_example.py    From Foundations-of-Blockchain with MIT License 5 votes vote down vote up
def verify(self):

        vk = VerifyingKey.from_string(bytes.fromhex(self.public_key), curve=SECP256k1)

        try:
            vk.verify(bytes.fromhex(self.signature), SHA256.new(str(self.id).encode()).digest())

        except keys.BadSignatureError:
            print('invalid transaction signature')
            return False

        return True 
Example #12
Source File: digital_signature_example.py    From Foundations-of-Blockchain with MIT License 5 votes vote down vote up
def sign(self, private_key):

        data_to_sign = SHA256.new(str(self.id).encode()).digest()

        sk = SigningKey.from_string(bytes.fromhex(private_key), curve=SECP256k1)
        self.signature = binascii.b2a_hex(sk.sign(data_to_sign)).decode() 
Example #13
Source File: keys.py    From python-bitcoin-utils with MIT License 5 votes vote down vote up
def _from_wif(self, wif):
        """Creates key from WIFC or WIF format key

        Check to_wif for the detailed process. From WIF is the reverse.

        Raises
        ------
        ValueError
            if the checksum is wrong or if the WIF/WIFC is not from the
            configured network.
        """

        wif_utf = wif.encode('utf-8')

        # decode base58check get key bytes plus checksum
        data_bytes = b58decode( wif_utf )
        key_bytes = data_bytes[:-4]
        checksum = data_bytes[-4:]

        # verify key with checksum
        data_hash = hashlib.sha256(hashlib.sha256(key_bytes).digest()).digest()
        if not checksum == data_hash[0:4]:
            raise ValueError('Checksum is wrong. Possible mistype?')

        # get network prefix and check with current setup
        network_prefix = key_bytes[:1]
        if NETWORK_WIF_PREFIXES[get_network()] != network_prefix:
            raise ValueError('Using the wrong network!')

        # remove network prefix
        key_bytes = key_bytes[1:]

        # check length of bytes and if > 32 then compressed
        # use this to instantite an ecdsa key
        if len(key_bytes) > 32:
            self.key = SigningKey.from_string(key_bytes[:-1], curve=SECP256k1)
        else:
            self.key = SigningKey.from_string(key_bytes, curve=SECP256k1) 
Example #14
Source File: Crypto.py    From neo-python with MIT License 5 votes vote down vote up
def VerifySignature(message, signature, public_key, unhex=True):
        """
        Verify the integrity of the message.

        Args:
            message (hexstr or str): the message to verify.
            signature (bytearray): the signature belonging to the message.
            public_key (ECPoint|bytes): the public key to use for verifying the signature. If `public_key` is of type bytes then it should be raw bytes (i.e. b'\xAA\xBB').
            unhex (bool): whether the message should be unhexlified before verifying

        Returns:
            bool: True if verification passes. False otherwise.
        """

        if type(public_key) is EllipticCurve.ECPoint:
            pubkey_x = public_key.x.value.to_bytes(32, 'big')
            pubkey_y = public_key.y.value.to_bytes(32, 'big')

            public_key = pubkey_x + pubkey_y

        if unhex:
            try:
                message = binascii.unhexlify(message)
            except binascii.Error:
                pass
        elif isinstance(message, str):
            message = message.encode('utf-8')

        if len(public_key) == 33:
            public_key = bitcoin.decompress(public_key)
            public_key = public_key[1:]

        try:
            vk = VerifyingKey.from_string(public_key, curve=NIST256p, hashfunc=hashlib.sha256)
            res = vk.verify(signature, message, hashfunc=hashlib.sha256)
            return res
        except Exception:
            pass

        return False 
Example #15
Source File: tools.py    From halocoin with Apache License 2.0 5 votes vote down vote up
def sign(msg, privkey):
    from ecdsa import SigningKey
    if isinstance(privkey, bytes):
        privkey = SigningKey.from_string(privkey)
    return privkey.sign(msg) 
Example #16
Source File: tools.py    From halocoin with Apache License 2.0 5 votes vote down vote up
def signature_verify(message, signature, pubkey):
    from ecdsa import VerifyingKey, SECP256k1
    if isinstance(pubkey, str):
        pubkey = VerifyingKey.from_string(pubkey, curve=SECP256k1)
    elif isinstance(pubkey, bytes):
        pubkey = VerifyingKey.from_string(pubkey, curve=SECP256k1)

    if isinstance(pubkey, VerifyingKey):
        try:
            return pubkey.verify(signature, message)
        except:
            return False
    else:
        return False 
Example #17
Source File: Crypto.py    From neo-python-core with MIT License 5 votes vote down vote up
def VerifySignature(message, signature, public_key, unhex=True):
        """
        Verify the integrity of the message.

        Args:
            message (str): the message to verify.
            signature (bytearray): the signature belonging to the message.
            public_key (ECPoint|bytes): the public key to use for verifying the signature. If `public_key` is of type bytes then it should be raw bytes (i.e. b'\xAA\xBB').
            unhex (bool): whether the message should be unhexlified before verifying

        Returns:
            bool: True if verification passes. False otherwise.
        """

        if type(public_key) is EllipticCurve.ECPoint:
            pubkey_x = public_key.x.value.to_bytes(32, 'big')
            pubkey_y = public_key.y.value.to_bytes(32, 'big')

            public_key = pubkey_x + pubkey_y

        if unhex:
            try:
                message = binascii.unhexlify(message)
            except Exception as e:
                logger.error("could not get m: %s" % e)
        elif isinstance(message, str):
            message = message.encode('utf-8')

        if len(public_key) == 33:
            public_key = bitcoin.decompress(public_key)
            public_key = public_key[1:]

        try:
            vk = VerifyingKey.from_string(public_key, curve=NIST256p, hashfunc=hashlib.sha256)
            res = vk.verify(signature, message, hashfunc=hashlib.sha256)
            return res
        except Exception as e:
            pass

        return False 
Example #18
Source File: bitcrack.py    From ecdsa-private-key-recovery with GNU General Public License v2.0 4 votes vote down vote up
def verify_vin_old(txid, index):

    # get raw transaction (txid)  <-- vin[0]: scriptSig
    rpc = BtcRpc("http://lala:lolo@127.0.0.1:8332")
    rawtx = rpc.rpc.getrawtransaction(txid)
    jsontxverbose = rpc.rpc.getrawtransaction(txid,1)
    #pprint.pprint(jsontxverbose)
    jsontx = pybitcointools.deserialize(rawtx)
    pprint.pprint(jsontx)
    scriptSigasm = jsontxverbose['vin'][index]['scriptSig']['asm']

    logger.debug(scriptSigasm)

    scriptSig = jsontx['ins'][index]['script']
    sigpubdecoded = asn1der.decode(scriptSig.decode("hex")[1:])  # skip first push
    sig = long(sigpubdecoded[0][0]), long(sigpubdecoded[0][1])
    pubkey = sigpubdecoded[1]
    sighash_type = pubkey[0]

    logger.debug("sighash type: %r" % sighash_type)
    push = pubkey[1]
    btc_pubkey_type = pubkey[2]
    pubkey = pubkey[3:]

    logger.debug("r %s s %s"%(hex(sig[0]),hex(sig[1])))
    logger.debug(pubkey.encode("hex"))
    # generate signdata
    # replace input script with funding script of 17SkEw2md5avVNyYgj6RiXuQKNwkXaxFyQ
    for txin in jsontx['ins']:
        txin['script']=''
    funding_txid = jsontxverbose['vin'][index]['txid']
    funding_tx = rpc.rpc.getrawtransaction(funding_txid,1)
    #pprint.pprint(funding_tx)
    funding_script = funding_tx['vout'][0]['scriptPubKey']['hex']
    jsontx['ins'][index]['script']=funding_script
    signdata= pybitcointools.serialize(jsontx) + "01000000"  #SIGHASH ALL
    import hashlib
    digest = hashlib.sha256(hashlib.sha256(signdata.decode("hex")).digest()).digest()
    logger.debug(digest[::-1].encode("hex"))

    vk = VerifyingKey.from_string(pubkey, curve=curve)
    logger.debug("verify --> %s "%(vk.pubkey.verifies(int(digest.encode("hex"),16),Signature(sig[0],sig[1]))))

    #print vk.verify_digest(scriptSigasm.split("[ALL]",1)[0].decode("hex"), digest, sigdecode=ecdsa.util.sigdecode_der)

    return BTCSignature(sig=Signature(sig[0],sig[1]),
                       h=int(digest.encode("hex"),16),
                       pubkey=pubkey,
                       ) 
Example #19
Source File: keys.py    From python-bitcoin-utils with MIT License 4 votes vote down vote up
def __init__(self, hex_str):
        """
        Parameters
        ----------
        hex_str : str
            the public key in hex string

        Raises
        ------
        TypeError
            If first byte of public key (corresponding to SEC format) is
            invalid.
        """

        # expects key as hex string - SEC format
        first_byte_in_hex = hex_str[:2] # 2 since a byte is represented by 2 hex characters
        hex_bytes = unhexlify(hex_str)

        # check if compressed or not
        if len(hex_bytes) > 33:
            # uncompressed - SEC format: 0x04 + x + y coordinates (x,y are 32 byte numbers)
            # remove first byte and instantiate ecdsa key
            self.key = VerifyingKey.from_string(hex_bytes[1:], curve=SECP256k1)
        else:
            # compressed - SEC FORMAT: 0x02|0x03 + x coordinate (if 02 then y
            # is even else y is odd. Calculate y and then instantiate the ecdsa key
            x_coord = int( hex_str[2:], 16 )

            # y = modulo_square_root( (x**3 + 7) mod p ) -- there will be 2 y values
            y_values = sqrt_mod( (x_coord**3 + 7) % _p, _p, True )

            # check SEC format's first byte to determine which of the 2 values to use
            if first_byte_in_hex == '02':
                # y is the even value
                if y_values[0] % 2 == 0:
                    y_coord = y_values[0]
                else:
                    y_coord = y_values[1]
            elif first_byte_in_hex == '03':
                # y is the odd value
                if y_values[0] % 2 == 0:
                    y_coord = y_values[1]
                else:
                    y_coord = y_values[0]
            else:
                raise TypeError("Invalid SEC compressed format")

            uncompressed_hex = "%0.64X%0.64X" % (x_coord, y_coord)
            uncompressed_hex_bytes = unhexlify(uncompressed_hex)
            self.key = VerifyingKey.from_string(uncompressed_hex_bytes, curve=SECP256k1)