當前位置: 首頁>>代碼示例>>Python>>正文


Python ecdsa.SECP256k1方法代碼示例

本文整理匯總了Python中ecdsa.SECP256k1方法的典型用法代碼示例。如果您正苦於以下問題:Python ecdsa.SECP256k1方法的具體用法?Python ecdsa.SECP256k1怎麽用?Python ecdsa.SECP256k1使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ecdsa的用法示例。


在下文中一共展示了ecdsa.SECP256k1方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: sign_ECDSA_msg

# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import SECP256k1 [as 別名]
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 
開發者ID:cosme12,項目名稱:SimpleCoin,代碼行數:16,代碼來源:wallet.py

示例2: sign

# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import SECP256k1 [as 別名]
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 
開發者ID:yummybian,項目名稱:blockchain-py,代碼行數:22,代碼來源:transaction.py

示例3: generate_ECDSA_keys

# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import SECP256k1 [as 別名]
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)) 
開發者ID:cosme12,項目名稱:SimpleCoin,代碼行數:21,代碼來源:wallet.py

示例4: verify

# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import SECP256k1 [as 別名]
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 
開發者ID:yummybian,項目名稱:blockchain-py,代碼行數:25,代碼來源:transaction.py

示例5: getPointByteSize

# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import SECP256k1 [as 別名]
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") 
開發者ID:scalyr,項目名稱:scalyr-agent-2,代碼行數:18,代碼來源:ecc.py

示例6: sign_vote

# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import SECP256k1 [as 別名]
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 
開發者ID:moocowmoo,項目名稱:dashman,代碼行數:23,代碼來源:dashutil.py

示例7: recover_message

# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import SECP256k1 [as 別名]
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) 
開發者ID:fetchai,項目名稱:agents-aea,代碼行數:25,代碼來源:cosmos.py

示例8: _recover_key

# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import SECP256k1 [as 別名]
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) 
開發者ID:eosnewyork,項目名稱:eospy,代碼行數:25,代碼來源:keys.py

示例9: validate_tx_in

# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import SECP256k1 [as 別名]
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 
開發者ID:PacktPublishing,項目名稱:Foundations-of-Blockchain,代碼行數:22,代碼來源:transaction.py

示例10: sign_tx_in

# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import SECP256k1 [as 別名]
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 
開發者ID:PacktPublishing,項目名稱:Foundations-of-Blockchain,代碼行數:25,代碼來源:transaction.py

示例11: __init__

# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import SECP256k1 [as 別名]
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) 
開發者ID:xeroc,項目名稱:python-graphenelib,代碼行數:18,代碼來源:account.py

示例12: from_privkey

# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import SECP256k1 [as 別名]
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) 
開發者ID:xeroc,項目名稱:python-graphenelib,代碼行數:20,代碼來源:account.py

示例13: validate_signature_for_spend

# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import SECP256k1 [as 別名]
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 
開發者ID:jamesob,項目名稱:tinychain,代碼行數:19,代碼來源:tinychain.py

示例14: init_wallet

# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import SECP256k1 [as 別名]
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
# ---------------------------------------------------------------------------- 
開發者ID:jamesob,項目名稱:tinychain,代碼行數:24,代碼來源:tinychain.py

示例15: validate_signature

# 需要導入模塊: import ecdsa [as 別名]
# 或者: from ecdsa import SECP256k1 [as 別名]
def validate_signature(public_key, signature, message):
    """Verifies if the signature is correct. This is used to prove
    it's you (and not someone else) trying to do a transaction with your
    address. Called when a user tries to submit a new transaction.
    """
    public_key = (base64.b64decode(public_key)).hex()
    signature = base64.b64decode(signature)
    vk = ecdsa.VerifyingKey.from_string(bytes.fromhex(public_key), curve=ecdsa.SECP256k1)
    # Try changing into an if/else statement as except is too broad.
    try:
        return vk.verify(signature, message.encode())
    except:
        return False 
開發者ID:cosme12,項目名稱:SimpleCoin,代碼行數:15,代碼來源:miner.py


注:本文中的ecdsa.SECP256k1方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。