Bitcoin地址的Base58Check编码过长

7 投票
1 回答
7703 浏览
提问于 2025-04-18 05:59

我正在用Python创建一个比特币地址。我已经搞定了哈希的部分,但在Base58Check编码上遇到了一些麻烦。我使用了这个包:

https://pypi.python.org/pypi/base58

这里有个例子:

import base58

unencoded_string = "00010966776006953D5567439E5E39F86A0D273BEED61967F6"
encoded_string = base58.b58encode(unencoded_string)
print(encoded_string)

输出结果是:

bSLesHPiFV9jKNeNbUiMyZGJm45zVSB8bSdogLWCmvs88wxHjEQituLz5daEGCrHE7R7

根据创建比特币地址的技术背景,上面的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

1 个回答

10

在使用 base58.b58encode 的时候,你需要传入的是字节(在 Python 2 中是 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 )) 来完成这个操作。

撰写回答