我有这段代码,它将用于根据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]发布于 2020-05-05 17:04:49
在sha256中,散列计算错误。不能执行Utf8编码。相反,熵必须表示为字节数组(请参阅to_bytes),并且散列必须由此生成:
import hashlib
def sha256(_entropy):
entBytes = int(_entropy, 2).to_bytes(len(_entropy) // 8, byteorder='big')
return hashlib.sha256(entBytes).hexdigest()此外,必须用长度为256位的前导0值填充散列(参见zfill),以便在校验和中也考虑前导0值:
def get_checksum(_entropy):
entropy_length = len(_entropy) // 32
return bin(int(sha256(_entropy), 16))[2:].zfill(256)[:entropy_length];示例1,来自here,步骤4:
_entropy = '0011001010000101011111010000101111111111101000001001000001001010110100010101111001001011000100111100011110001001111011110111011010010100110011001110111001100010111011010010101101010011110100100110101111110001100101011001000110100010000110110001100101110001'
print(get_checksum(_entropy)) # 11110011示例2,您的第二个示例:
_entropy = '01011010000000110011001001001001001110100011100101010001001100111001111111000110000000011011110111011000011001010111001101111100'
print(get_checksum(_entropy)) # 1110示例3,前导0值,与here的结果进行比较:
_entropy = '10111101100011110111100011101111111110100010000101111110100101100000001100111111001100010010010011110110011011010010001011011000'
print(get_checksum(_entropy)) # 0010https://stackoverflow.com/questions/61596962
复制相似问题