首页 文章

在python 3.6中生成比特币密钥对,从公钥到公共地址

提问于
浏览
2

我有一个关于我正在尝试编写的脚本的问题,该脚本会为比特币格式生成密钥对 . 我来到生成随机私钥并生成公钥 . 我知道(或者真的想多少?)我的第一部分代码是正确的 . 当我转到bitaddress.org并检查我生成的私钥以获取详细信息时,我总是得到正确生成的公钥 .

这就是我现在拥有的

import os
import ecdsa
import binascii

private_key = binascii.hexlify(os.urandom(32)).decode()
print("private key = " + private_key)

Private_key = bytes.fromhex(private_key)

signing_key = ecdsa.SigningKey.from_string(Private_key, curve = ecdsa.SECP256k1)
verifying_key = signing_key.get_verifying_key()

public_key = bytes.fromhex("04") + verifying_key.to_string()
print ("public key = " + public_key.hex())

问题是,现在我得到130个字符的公钥,我想将其转换为比特币地址 . 我不明白该怎么做 . 我需要做一些编码/解码,但无法绕过它 . 这是我发现的互联网的解释,但没有理解:

Bitcoin address explanation png

有人可能会帮我这个

1 回答

  • 1

    此代码在Python 2和Python 3中运行 . 它不仅打印比特币地址,还打印一些中间值 . 公钥是 pubkey 变量中的130十六进制字符串 .

    请注意there are two possible and valid bitcoin addresses for each public key:未压缩和压缩的表单 . 更改 compress_key 布尔变量以提取每个变量 .

    #!/usr/bin/env python
    # https://en.bitcoin.it/wiki/Protocol_documentation#Addresses
    
    import hashlib
    import base58
    
    # ECDSA bitcoin Public Key
    pubkey = '0450863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b23522cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6'
    # See 'compressed form' at https://en.bitcoin.it/wiki/Protocol_documentation#Signatures
    compress_pubkey = False
    
    
    def hash160(hex_str):
        sha = hashlib.sha256()
        rip = hashlib.new('ripemd160')
        sha.update(hex_str)
        rip.update( sha.digest() )
        print ( "key_hash = \t" + rip.hexdigest() )
        return rip.hexdigest()  # .hexdigest() is hex ASCII
    
    
    if (compress_pubkey):
        if (ord(bytearray.fromhex(pubkey[-2:])) % 2 == 0):
            pubkey_compressed = '02'
        else:
            pubkey_compressed = '03'
        pubkey_compressed += pubkey[2:66]
        hex_str = bytearray.fromhex(pubkey_compressed)
    else:
        hex_str = bytearray.fromhex(pubkey)
    
    # Obtain key:
    
    key_hash = '00' + hash160(hex_str)
    
    # Obtain signature:
    
    sha = hashlib.sha256()
    sha.update( bytearray.fromhex(key_hash) )
    checksum = sha.digest()
    sha = hashlib.sha256()
    sha.update(checksum)
    checksum = sha.hexdigest()[0:8]
    
    print ( "checksum = \t" + sha.hexdigest() )
    print ( "key_hash + checksum = \t" + key_hash + ' ' + checksum )
    print ( "bitcoin address = \t" + base58.b58encode( bytes(bytearray.fromhex(key_hash + checksum)) ) )
    

相关问题