查找具有 5 个前导零的字符串的哈希值

Finding hash with 5 leading zeros for a string

我正在做一个散列难题来理解 sha256 机制。也许有人可以帮我处理代码。

1-我要找一个小的,十六进制前4-5位为0的nonce

2- 编写一个函数,将您的姓名和哈希中前导零的数量作为输入

3- 它应该有一个从零开始的随机数(计数器),它将在每个 SHA256 哈希轮次之前附加到字符串中

4- 循环应继续散列并递增 nonce,直到找到目标散列 最后,打印哈希值、最终原像、查找哈希值的尝试次数以及以秒为单位的总执行时间

示例输出:

为字符串 Omar 查找带有 5 个零的散列(这是描述性的)。

    Found hash 00000def2d1265b4f95f556f33b97b935016d7cd92fdfd7e9208cda1e887f6b4
    Number of attemts: 2743370 
    Execution time: 7.635315895080566 seconds
    Final pre-image: Omar2743370

到目前为止,这是我想出的

y = 1
found = 0
while found == 0:
    hh = hashlib.sha256(str(y).encode()).hexdigest()
    if hh[:4] == "0000":
        found = 1
    y +=1
print(hh)
print(y)

这是一种方法:

from hashlib import sha256
from time import perf_counter

def main(name, lz):
    attempts = 1
    prefix = '0' * lz
    while not (hash_ := sha256(f'{name}{attempts}'.encode()).hexdigest()).startswith(prefix):
        attempts += 1
    return name, hash_, attempts

for lz in 4, 5:
    start = perf_counter()
    name, hash_, attempts = main('Omar', lz)
    end = perf_counter()
    print(f'Found hash: {hash_}')
    print(f'Number of attempts: {attempts}')
    print(f'Execution time: {end-start:.15f} seconds')
    print(f'Final pre-image: {name}{attempts}\n')

输出:

Found hash: 00004b8def35c72c9313253e242cdef508151dda5213efbead0386202ca38959
Number of attempts: 18102
Execution time: 0.018010623003647 seconds
Final pre-image: Omar18102

Found hash: 000004a5f963f6dc40afded7e20d1471649764af87f700d6b01b3976dd7623f1
Number of attempts: 986924
Execution time: 0.952605198996025 seconds
Final pre-image: Omar986924