首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >BIP39校验和有时会失败

BIP39校验和有时会失败
EN

Stack Overflow用户
提问于 2020-05-05 00:25:48
回答 1查看 435关注 0票数 1

我有这段代码,它将用于根据BIP39 Spec实现助记短语生成器。问题是大多数时候校验和是不正确的,但在某些情况下它是有效的,它取决于给定的熵。(我使用了iancoleman.io bip39来测试我的校验和)。

观察到了以下情况:

使用了128位的熵。

代码语言:javascript
复制
Correct
Entropy:  10111101100010110111100011101111111110100010000101111110100101100000001100111111001100010010010011110110011010010010001011011000
Checksum: 1110

Incorrect
Entropy:  01011010000000110011001001001001001110100011100101010001001100111001111111000110000000011011110111011000011001010111001101111100
My checksum: 1010
Iancoleman checksum:1110

第一个是成功的案例,但第二个失败了。下面你可以找到我的函数。

我错过了什么?

代码语言:javascript
复制
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]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-05 17:04:49

sha256中,散列计算错误。不能执行Utf8编码。相反,熵必须表示为字节数组(请参阅to_bytes),并且散列必须由此生成:

代码语言:javascript
复制
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值:

代码语言:javascript
复制
def get_checksum(_entropy):
    entropy_length = len(_entropy) // 32
    return bin(int(sha256(_entropy), 16))[2:].zfill(256)[:entropy_length];

示例1,来自here,步骤4:

代码语言:javascript
复制
_entropy = '0011001010000101011111010000101111111111101000001001000001001010110100010101111001001011000100111100011110001001111011110111011010010100110011001110111001100010111011010010101101010011110100100110101111110001100101011001000110100010000110110001100101110001'
print(get_checksum(_entropy)) # 11110011

示例2,您的第二个示例:

代码语言:javascript
复制
_entropy = '01011010000000110011001001001001001110100011100101010001001100111001111111000110000000011011110111011000011001010111001101111100'
print(get_checksum(_entropy)) # 1110

示例3,前导0值,与here的结果进行比较:

代码语言:javascript
复制
_entropy = '10111101100011110111100011101111111110100010000101111110100101100000001100111111001100010010010011110110011011010010001011011000'
print(get_checksum(_entropy)) # 0010
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61596962

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档