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



我正在做一个哈希谜题来理解sha256机制。也许有人能帮我写代码。

1-我需要找到一个较小的nonce,并且前4-5位数字在十六进制记数法中为0。

2-编写一个函数,取你的名字和作为输入

的哈希中前导零的个数3-它应该有一个从0开始的nonce(计数器),它将在每个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

最新更新