Python3 Crypto.Hash - SHA 摘要总是以二进制 1 开头

Python3 Crypto.Hash - SHA digest always starts with binary 1

我正在做一个项目,试图创建一个非常简单的基于区块链的加密货币。这是我尝试对块对象进行哈希处理的方式的过度简化版本(显然 Block class 的字段要复杂得多,但这是主要思想):

from Crypto.Hash import SHA
import json
from collections import OrderedDict
from random import random

class Block(object):

    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

    def to_dict(self):
        d = OrderedDict({
            'x' : self.x,
            'y' : self.y,
            'z' : self.z
        })
        return d

    def json(self):
        return json.dumps(self.to_dict())

    def hash(self):
        return SHA.new(self.json().encode('utf8')).hexdigest()

# driver code to test hashing
while True:
    x, y, z = [random() for _ in range(3)]
    b = Block(x, y, z)
    if not bin(int(b.hash(), 16)).startswith('0b1'):
        break

上面的驱动程序一直循环下去。问题是(无论字段的数值 and/or 值如何)散列总是以 0b1 开头,这与挖掘难度和工作量证明的整个概念相混淆。不过,更重要的是,这不是散列函数的预期行为。我想念什么?

Python默认不对二进制数前面补零,所以任何二进制数的第一位都是1。

>>> bin(1)
'0b1'
>>> bin(2)
'0b10'
>>> bin(3)
'0b11'
>>> bin(8)
'0b1000'

如果要固定二进制字符串,请使用字符串格式

>>> "{:04b}".format(1)
'0001'
>>> "{:04b}".format(2)
'0010'
>>> "{:04b}".format(8)
'1000'
>>> "{:04b}".format(15)
'1111'

否则,只需使用二进制和 (&) 来检查是否设置了特定位。

>>> bool(1 & 0b1000)
False
>>> bool(3 & 0b1000)
False
>>> bool(8 & 0b1000)
True
>>> bool(15 & 0b1000)
True