我正在尝试使用 Python 创建一个比特币地址。我的散列部分是正确的,但我在 Base58Check 编码方面遇到了一些问题。我使用这个包:
https://pypi.python.org/pypi/base58
这是一个例子:
import base58
unencoded_string = "00010966776006953D5567439E5E39F86A0D273BEED61967F6"
encoded_string = base58.b58encode(unencoded_string)
print(encoded_string)
输出是:
bSLesHPiFV9jKNeNbUiMyZGJm45zVSB8bSdogLWCmvs88wxHjEQituLz5daEGCrHE7R7
根据 the technical background for creating Bitcoin addresses上面的 RIPEMD-160 哈希应该是“16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM”。也就是说,我的输出是错误的,而且显然太长了。有谁知道我做错了什么?
编辑:
我添加了一个十六进制解码(.decode("hex")):
import base58
unencoded_string = "00010966776006953D5567439E5E39F86A0D273BEED61967F6"
encoded_string = base58.b58encode(unencoded_string.decode("hex"))
print(encoded_string)
现在输出看起来更好了:
1csU3KSAQMEYLPudM8UWJVxFfptcZSDvaYY477
然而,它仍然是错误的。它必须是字节编码吗?你如何在 Python 中做到这一点?
编辑2:
现在修复了它(感谢 Arpegius)。将 str(bytearray.fromhex( hexstring )) 添加到我的代码中(在 Python 2.7 中):
import base58
hexstring= "00010966776006953D5567439E5E39F86A0D273BEED61967F6"
unencoded_string = str(bytearray.fromhex( hexstring ))
encoded_string= base58.b58encode(unencoded_string)
print(encoded_string)
输出:
16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM
最佳答案
在 base58.b58encode
中需要字节 (python2 str) 而不是十六进制。您需要先对其进行解码:
In [1]: import base58
In [2]: hexstring= "00010966776006953D5567439E5E39F86A0D273BEED61967F6"
In [3]: unencoded_string = bytes.fromhex(hexstring)
In [4]: encoded_string= base58.b58encode(unencoded_string)
In [5]: print(encoded_string)
16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM
在 python 2.7 中,您可以使用 str(bytearray.fromhex( hexstring ))
。
关于python - 比特币地址的 Base58Check 编码太长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23565083/