且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python 2.7将比特币Privkey转换为WIF Privkey

更新时间:2023-11-04 09:26:58

您可能从 Bitcoin Wiki的理解中被误解了步骤是所有的哈希和填充必须在键上以 bytes (而不是字符串)完成.

What you probably misunderstood from the Bitcoin Wiki's steps is that all the hashing and stuff must be done on the keys as bytes, not as strings.

这意味着,如果您想从私钥"29a59..."派生WIF密钥,则不必对字符串 "8029a59..."进行哈希处理,而只需对二进制数据进行哈希处理>与此相对应.

This means that if you want to derive the WIF key from your Private key "29a59..." you don't have to hash the string "8029a59..." but the binary data that corresponds to it instead.

这是有效的缺少代码段

# importing binascii to be able to convert hexadecimal strings to binary data
import binascii

# Step 1: here we have the private key
private_key_static = "29a59e66fe370e901174a1b8296d31998da5588c7e0dba860f11d65a3adf2736"
# Step 2: let's add 80 in front of it
extended_key = "80"+private_key_static
# Step 3: first SHA-256
first_sha256 = hashlib.sha256(binascii.unhexlify(extended_key)).hexdigest()
# Step 4: second SHA-256
second_sha256 = hashlib.sha256(binascii.unhexlify(first_sha256)).hexdigest()
# Step 5-6: add checksum to end of extended key
final_key = extended_key+second_sha256[:8]
# Step 7: finally the Wallet Import Format is the base 58 encode of final_key
WIF = base58.b58encode(binascii.unhexlify(final_key))
print (WIF)

其中 binascii.unhexlify(...) 告诉我们所表示的二进制数据用十六进制字符串表示.

where binascii.unhexlify(...) tells us the binary data represented by the hexadecimal string.

其余的代码也可以正常工作;)

The rest of your code works just fine ;)