Skip to main content
 首页 » 编程设计

python之在python 3.6中从公钥到公共(public)地址生成比特币 key 对

2024年10月01日8java哥

我有一个关于我正在尝试编写的脚本的问题,该脚本为比特币地址生成 key 对。我就生成了一个随机私钥并生成了一个公钥。我知道(或者想得很多?)我的第一部分代码是正确的。当我去 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

谁能帮我解决这个问题

请您参考如下方法:

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

请注意there are two possible and valid bitcoin addresses for each public key : 未压缩和压缩的形式。更改 compress_key bool 变量以提取每个。

#!/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)) ) )