当前位置: 首页>>代码示例>>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;未经允许,请勿转载。