【发布时间】:2020-05-04 16:25:47
【问题描述】:
我有这个 sn-p 代码,它将用于根据BIP39 Spec 实现助记词生成器。 问题是大多数时候校验和不正确,但在某些情况下它有效,这取决于给定的熵。 (我使用iancoleman.io bip39 来测试我的校验和)。
观察到以下情况:
使用了 128 位的熵。
Correct
Entropy: 10111101100010110111100011101111111110100010000101111110100101100000001100111111001100010010010011110110011010010010001011011000
Checksum: 1110
Incorrect
Entropy: 01011010000000110011001001001001001110100011100101010001001100111001111111000110000000011011110111011000011001010111001101111100
My checksum: 1010
Iancoleman checksum:1110
第一个是成功的案例,但第二个失败了。您可以在下面找到我的功能。
我错过了什么?
def fill_bits(binary, bits):
if len(binary) < bits:
return "0" * (bits - len(binary)) + binary
return binary
# generate a given number of entropy bits
def generate_entropy(bits=256):
if bits < 128 or bits > 256:
raise EntropyRangeExceeded
entropybits = bin(int.from_bytes(os.urandom(bits // 8), byteorder=sys.byteorder))[2:]
return fill_bits(entropybits, bits)
# returns the sha256 hash of the given input
def sha256(_input):
return hashlib.sha256(_input.encode("utf-8")).hexdigest()
# returns the checksum of the input hash
# checksum is given by the first (entropy length / 32)
# bits of the sha256 hash applied on entropy bits
def get_checksum(_entropy):
entropy_length = len(_entropy) // 32
return bin(int(sha256(_entropy), 16))[2:][:entropy_length]
【问题讨论】:
标签: cryptography python-3.7 bitcoin checksum cryptocurrency