Python ecdsa.SECP256k1() Examples

The following are 30 code examples of ecdsa.SECP256k1(). 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 , or try the search function .
Example #1
Source File: cosmos.py    From agents-aea with Apache License 2.0 8 votes vote down vote up
def recover_message(
        self, message: bytes, signature: str, is_deprecated_mode: bool = False
    ) -> Tuple[Address, ...]:
        """
        Recover the addresses from the hash.

        :param message: the message we expect
        :param signature: the transaction signature
        :param is_deprecated_mode: if the deprecated signing was used
        :return: the recovered addresses
        """
        signature_b64 = base64.b64decode(signature)
        verifying_keys = VerifyingKey.from_public_key_recovery(
            signature_b64, message, SECP256k1, hashfunc=hashlib.sha256,
        )
        public_keys = [
            verifying_key.to_string("compressed").hex()
            for verifying_key in verifying_keys
        ]
        addresses = [
            self.get_address_from_public_key(public_key) for public_key in public_keys
        ]
        return tuple(addresses) 
Example #2
Source File: tinychain.py    From tinychain with MIT License 7 votes vote down vote up
def validate_signature_for_spend(txin, utxo: UnspentTxOut, txn):
    pubkey_as_addr = pubkey_to_address(txin.unlock_pk)
    verifying_key = ecdsa.VerifyingKey.from_string(
        txin.unlock_pk, curve=ecdsa.SECP256k1)

    if pubkey_as_addr != utxo.to_address:
        raise TxUnlockError("Pubkey doesn't match")

    try:
        spend_msg = build_spend_message(
            txin.to_spend, txin.unlock_pk, txin.sequence, txn.txouts)
        verifying_key.verify(txin.unlock_sig, spend_msg)
    except Exception:
        logger.exception('Key verification failed')
        raise TxUnlockError("Signature doesn't match")

    return True 
Example #3
Source File: wallet.py    From SimpleCoin with MIT License 6 votes vote down vote up
def sign_ECDSA_msg(private_key):
    """Sign the message to be sent
    private_key: must be hex

    return
    signature: base64 (to make it shorter)
    message: str
    """
    # Get timestamp, round it, make it into a string and encode it to bytes
    message = str(round(time.time()))
    bmessage = message.encode()
    sk = ecdsa.SigningKey.from_string(bytes.fromhex(private_key), curve=ecdsa.SECP256k1)
    signature = base64.b64encode(sk.sign(bmessage))
    return signature, message 
Example #4
Source File: tinychain.py    From tinychain with MIT License 6 votes vote down vote up
def init_wallet(path=None):
    path = path or WALLET_PATH

    if os.path.exists(path):
        with open(path, 'rb') as f:
            signing_key = ecdsa.SigningKey.from_string(
                f.read(), curve=ecdsa.SECP256k1)
    else:
        logger.info(f"generating new wallet: '{path}'")
        signing_key = ecdsa.SigningKey.generate(curve=ecdsa.SECP256k1)
        with open(path, 'wb') as f:
            f.write(signing_key.to_string())

    verifying_key = signing_key.get_verifying_key()
    my_address = pubkey_to_address(verifying_key.to_string())
    logger.info(f"your address is {my_address}")

    return signing_key, verifying_key, my_address


# Misc. utilities
# ---------------------------------------------------------------------------- 
Example #5
Source File: account.py    From python-graphenelib with MIT License 6 votes vote down vote up
def from_privkey(cls, privkey, prefix=None):
        """ Derive uncompressed public key """
        privkey = PrivateKey(privkey, prefix=prefix or Prefix.prefix)
        secret = unhexlify(repr(privkey))
        order = ecdsa.SigningKey.from_string(
            secret, curve=ecdsa.SECP256k1
        ).curve.generator.order()
        p = ecdsa.SigningKey.from_string(
            secret, curve=ecdsa.SECP256k1
        ).verifying_key.pubkey.point
        x_str = ecdsa.util.number_to_string(p.x(), order)
        # y_str = ecdsa.util.number_to_string(p.y(), order)
        compressed = hexlify(chr(2 + (p.y() & 1)).encode("ascii") + x_str).decode(
            "ascii"
        )
        # uncompressed = hexlify(
        #    chr(4).encode('ascii') + x_str + y_str).decode('ascii')
        return cls(compressed, prefix=prefix or Prefix.prefix) 
Example #6
Source File: account.py    From python-graphenelib with MIT License 6 votes vote down vote up
def __init__(self, pk, prefix=None):
        self.set_prefix(prefix)
        if isinstance(pk, PublicKey):
            pk = format(pk, self.prefix)

        if str(pk).startswith("04"):
            # We only ever deal with compressed keys, so let's make it
            # compressed
            order = ecdsa.SECP256k1.order
            p = ecdsa.VerifyingKey.from_string(
                unhexlify(pk[2:]), curve=ecdsa.SECP256k1
            ).pubkey.point
            x_str = ecdsa.util.number_to_string(p.x(), order)
            pk = hexlify(chr(2 + (p.y() & 1)).encode("ascii") + x_str).decode("ascii")

        self._pk = Base58(pk, prefix=self.prefix) 
Example #7
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 #8
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 #9
Source File: keys.py    From eospy with MIT License 6 votes vote down vote up
def _recover_key(self, digest, signature, i) :
        ''' Recover the public key from the sig
            http://www.secg.org/sec1-v2.pdf
        '''
        curve = ecdsa.SECP256k1.curve
        G = ecdsa.SECP256k1.generator
        order = ecdsa.SECP256k1.order
        yp = (i %2)
        r, s = ecdsa.util.sigdecode_string(signature, order)
        x = r + (i // 2 ) * order
        alpha = ((x * x * x) + (curve.a() * x) + curve.b()) % curve.p()
        beta = ecdsa.numbertheory.square_root_mod_prime(alpha, curve.p())
        y = beta if (beta - yp) % 2 == 0 else curve.p() - beta
        # generate R
        R = ecdsa.ellipticcurve.Point(curve, x, y, order)
        e = ecdsa.util.string_to_number(digest)
        # compute Q
        Q = ecdsa.numbertheory.inverse_mod(r, order) * (s * R + (-e % order) * G)
        # verify message
        if not ecdsa.VerifyingKey.from_public_point(Q, curve=ecdsa.SECP256k1).verify_digest(signature, digest,
                                                                                            sigdecode=ecdsa.util.sigdecode_string) :
            return None
        return ecdsa.VerifyingKey.from_public_point(Q, curve=ecdsa.SECP256k1) 
Example #10
Source File: dashutil.py    From dashman with MIT License 6 votes vote down vote up
def sign_vote(votestr, mnprivkey):
    privatekey = utils.wifToPrivateKey(mnprivkey)
    signingkey = Bip62SigningKey.from_string(
        privatekey.decode('hex'),
        curve=ecdsa.SECP256k1)
    public_key = signingkey.get_verifying_key()
    key = Key.from_text(mnprivkey)
    address = key.address(use_uncompressed=True)
    msghash = utils.double_sha256(utils.msg_magic(votestr))
    signature = signingkey.sign_digest_deterministic(
        msghash,
        hashfunc=hashlib.sha256,
        sigencode=ecdsa.util.sigencode_string)
    assert public_key.verify_digest(
        signature,
        msghash,
        sigdecode=ecdsa.util.sigdecode_string)
    for i in range(4):
        sig = base64.b64encode(chr(27+i) + signature)
        if verify_dash_signature(generator_secp256k1, address, msghash, sig):
            return sig 
Example #11
Source File: ecc.py    From scalyr-agent-2 with Apache License 2.0 6 votes vote down vote up
def getPointByteSize(point):
    """Convert the point or curve bit size to bytes"""
    curveMap = {ecdsa.NIST256p.curve: 256//8,
                ecdsa.NIST384p.curve: 384//8,
                ecdsa.NIST521p.curve: (521+7)//8,
                ecdsa.SECP256k1.curve: 256//8}
    if ecdsaAllCurves:
        curveMap[ecdsa.NIST224p.curve] = 224//8
        curveMap[ecdsa.NIST192p.curve] = 192//8

    if hasattr(point, 'curve'):
        if callable(point.curve):
            return curveMap[point.curve()]
        else:
            return curveMap[point.curve]
    raise ValueError("Parameter must be a curve or point on curve") 
Example #12
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 #13
Source File: wallet.py    From SimpleCoin with MIT License 6 votes vote down vote up
def generate_ECDSA_keys():
    """This function takes care of creating your private and public (your address) keys.
    It's very important you don't lose any of them or those wallets will be lost
    forever. If someone else get access to your private key, you risk losing your coins.

    private_key: str
    public_ley: base64 (to make it shorter)
    """
    sk = ecdsa.SigningKey.generate(curve=ecdsa.SECP256k1) #this is your sign (private key)
    private_key = sk.to_string().hex() #convert your private key to hex
    vk = sk.get_verifying_key() #this is your verification key (public key)
    public_key = vk.to_string().hex()
    #we are going to encode the public key to make it shorter
    public_key = base64.b64encode(bytes.fromhex(public_key))

    filename = input("Write the name of your new address: ") + ".txt"
    with open(filename, "w") as f:
        f.write("Private key: {0}\nWallet address / Public key: {1}".format(private_key, public_key.decode()))
    print("Your new address and private key are now in the file {0}".format(filename)) 
Example #14
Source File: crypto.py    From btcpy with GNU Lesser General Public License v3.0 6 votes vote down vote up
def raw_sign(self, data, deterministic=True):
        sig_key = SigningKey.from_string(self.key, curve=SECP256k1)
        sig_func = partial(sig_key.sign_digest_deterministic, hashfunc=sha256) if deterministic else sig_key.sign_digest
        r, s, order = sig_func(data, sigencode=lambda *x: x)
        if s < 0x01:
            raise ValueError('Too low s value for signature: {}'.format(s))
        # ref: https://github.com/bitcoin/bips/blob/master/bip-0062.mediawiki#Low_S_values_in_signatures
        if s > PrivateKey.highest_s:
            s = order - s
        if s.to_bytes(32, 'big')[0] > 0x7f:
            s = int.from_bytes(b'\x00' + s.to_bytes(32, 'big'), 'big')
        if r.to_bytes(32, 'big')[0] > 0x7f:
            r = int.from_bytes(b'\x00' + r.to_bytes(32, 'big'), 'big')
        return r, s, order 
Example #15
Source File: core.py    From pyquarkchain with MIT License 6 votes vote down vote up
def create_from_key(key):
        sk = ecdsa.SigningKey.from_string(key, curve=ecdsa.SECP256k1)
        recipient = sha3_256(sk.verifying_key.to_string())[-20:]
        return Identity(recipient, key) 
Example #16
Source File: crypto.py    From btcpy with GNU Lesser General Public License v3.0 6 votes vote down vote up
def pub(self, compressed=None):
        if compressed is None:
            compressed = self.public_compressed
        raw_pubkey = bytearray(SigningKey.from_string(self.key, curve=SECP256k1).get_verifying_key().to_string())
        uncompressed = PublicKey(bytearray([0x04]) + raw_pubkey)
        if compressed:
            return PublicKey(uncompressed.compressed)
        else:
            return uncompressed 
Example #17
Source File: transaction.py    From blockchain-py with Apache License 2.0 6 votes vote down vote up
def verify(self, prev_txs):
        for vin in self.vin:
            if not prev_txs[vin.tx_id].ID:
                # log.error("Previous transaction is not correct")
                print("Previous transaction is not correct")

        tx_copy = self._trimmed_copy()

        for in_id, vin in enumerate(self.vin):
            prev_tx = prev_txs[vin.tx_id]
            tx_copy.vin[in_id].signature = None
            tx_copy.vin[in_id].public_key = prev_tx.vout[vin.vout].public_key_hash
            tx_copy.ID = tx_copy.hash()
            tx_copy.vin[in_id].public_key = None

            sig = self.vin[in_id].signature
            # vk = ecdsa.VerifyingKey.from_string(
            #     vin.public_key[2:], curve=ecdsa.SECP256k1)
            vk = utils.pubkey_to_verifykey(vin.public_key)
            if not vk.verify(sig, utils.encode(tx_copy.ID)):
                return False

        return True 
Example #18
Source File: transaction.py    From blockchain-py with Apache License 2.0 6 votes vote down vote up
def sign(self, priv_key, prev_txs):
        for vin in self.vin:
            if not prev_txs[vin.tx_id].ID:
                # log.error("Previous transaction is not correct")
                print("Previous transaction is not correct")

        tx_copy = self._trimmed_copy()

        for in_id, vin in enumerate(tx_copy.vin):
            prev_tx = prev_txs[vin.tx_id]
            tx_copy.vin[in_id].signature = None
            tx_copy.vin[in_id].public_key = prev_tx.vout[vin.vout].public_key_hash
            tx_copy.ID = tx_copy.hash()
            tx_copy.vin[in_id].public_key = None

            sk = ecdsa.SigningKey.from_string(
                priv_key, curve=ecdsa.SECP256k1)
            sig = sk.sign(utils.encode(tx_copy.ID))

            self.vin[in_id].signature = sig 
Example #19
Source File: utils.py    From blockchain-py with Apache License 2.0 5 votes vote down vote up
def pubkey_to_verifykey(pub_key, curve=ecdsa.SECP256k1):
    vk_string = binascii.unhexlify(encode(pub_key[2:]))
    return ecdsa.VerifyingKey.from_string(vk_string, curve=curve) 
Example #20
Source File: http.py    From storj-python-sdk with MIT License 5 votes vote down vote up
def key_generate(self):

        self.logger.info('key_generate()')

        self.logger.debug('This will replace your public and private keys in 3 seconds...')
        time.sleep(3)

        self.private_key = SigningKey.generate(curve=SECP256k1, hashfunc=sha256)
        self.public_key = self.private_key.get_verifying_key()

        s = raw_input('Export keys to file for later use? [Y/N]')
        if 'Y' in s.upper():
            self.key_export()

        self.key_register(self.public_key) 
Example #21
Source File: __init__.py    From ecdsa-private-key-recovery with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, sig, h, pubkey, curve=ecdsa.SECP256k1):
        self.curve = curve  # must be set before __init__ calls __load_pubkey

        super(EcDsaSignature, self).__init__(sig, h, pubkey)

        self.signingkey = None
        self.n = self.pubkey.generator.order()

        logger.debug("%r - check verifies.." % self)
        assert (self.pubkey.verifies(self.h, self.sig))
        logger.debug("%r - Signature is ok" % self) 
Example #22
Source File: test_ecdsa_key_recovery.py    From ecdsa-private-key-recovery with GNU General Public License v2.0 5 votes vote down vote up
def test_nonce_reuse(pub=None, curve=ecdsa.SECP256k1):
            if not pub:
                # default
                pub = ecdsa.VerifyingKey.from_string(
                    "a50eb66887d03fe186b608f477d99bc7631c56e64bb3af7dc97e71b917c5b3647954da3444d33b8d1f90a0d7168b2f158a2c96db46733286619fccaafbaca6bc".decode(
                        "hex"), curve=curve).pubkey
            # static testcase
            # long r, long s, bytestr hash, pubkey obj.
            sampleA = EcDsaSignature((3791300999159503489677918361931161866594575396347524089635269728181147153565,
                                      49278124892733989732191499899232294894006923837369646645433456321810805698952),
                                     bignum_to_hex(
                                         765305792208265383632692154455217324493836948492122104105982244897804317926).decode(
                                         "hex"),
                                     pub)
            sampleB = EcDsaSignature((3791300999159503489677918361931161866594575396347524089635269728181147153565,
                                      34219161137924321997544914393542829576622483871868414202725846673961120333282),
                                     bignum_to_hex(
                                         23350593486085962838556474743103510803442242293209938584974526279226240784097).decode(
                                         "hex"),
                                     pub)

            assert (sampleA.x is None)  # not yet resolved
            logger.debug("%r - recovering private-key from nonce reuse ..." % sampleA)
            sampleA.recover_nonce_reuse(sampleB)
            assert (sampleA.x is not None)  # privkey recovered
            assert sampleA.privkey
            logger.debug("%r - Private key recovered! \n%s" % (sampleA, sampleA.export_key()))

    # noinspection PyClassHasNoInit 
Example #23
Source File: bitcrack.py    From ecdsa-private-key-recovery with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, sig, h, pubkey, curve=ecdsa.SECP256k1):
        super(BTCSignature, self).__init__(sig, h, BTCSignature._fix_pubkey(pubkey), curve=curve) 
Example #24
Source File: miner_address.py    From pyquarkchain with MIT License 5 votes vote down vote up
def gen_address():
    sk = ecdsa.SigningKey.generate(curve=ecdsa.SECP256k1)
    print(
        colorify(
            "A new address has been generated for you, your private key is: ", "grey"
        )
    )
    print(sk.to_string().hex())
    address = sha3_256(sk.verifying_key.to_string())[-20:].hex()
    print(colorify("Address is:", "grey") + " 0x{}".format(address))
    return address 
Example #25
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 #26
Source File: wallet.py    From Foundations-of-Blockchain with MIT License 5 votes vote down vote up
def get_public_from_wallet():

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

    sk = SigningKey.generate(curve=SECP256k1)
    with open(PRIV_KEY_LOC, 'wt') as file_obj:
        file_obj.write(binascii.b2a_hex(sk.to_string()).decode()) 
Example #28
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 #29
Source File: digital_signature_example.py    From Foundations-of-Blockchain with MIT License 5 votes vote down vote up
def generate_key_pair(self):

        sk = SigningKey.generate(curve=SECP256k1)
        self.private_key = binascii.b2a_hex(sk.to_string()).decode()
        self.public_key = binascii.b2a_hex(sk.get_verifying_key().to_string()).decode() 
Example #30
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