首页 > 解决方案 > 如何散列给定范围的已散列值?

问题描述

我正在尝试设计一种一次性密码算法。我想从用户那里得到一个字符串输入,并重复哈希它 100 次,然后将每个存储到一个数组中。我被困在需要反复散列字符串的部分。

我已经尝试了基础知识,我知道如何使用 hashlib 获取字符串值的哈希值。在下面的代码中,我尝试以这种方式应用它 10 次,但我觉得有一种更简单的方法可以实际工作。

import hashlib

hashStore= []

password= input("Password to hash converter: ")
hashedPassword= hashlib.md5(password.encode())
print("Your hash is: ", hashedPassword.hexdigest())

while i in range(1,10):
    reHash= hashlib.md5(hashedPassword)
    hashStore.append(rehash)
    i= i+1
    print("Rehashed ",reHash.hexdigest())

但是,此代码不起作用。我希望它能够“重新散列”该值,并且每次都将其添加到数组中。

任何和所有的帮助表示赞赏:)

标签: pythonpython-3.xcryptographymd5hashlib

解决方案


  1. Python 中的 for 循环可以更容易地实现。只需for i in range(10):在循环里面不写任何东西。

  2. hashStore.append(rehash)使用rehash而不是reHash

  3. 你不会记住你的reHash所以你总是尝试散列起始字符串

  4. 如果你想重新散列它,你应该将你的散列转换为字符串:reHash.hexdigest().encode('utf-8')

这是完整的工作代码:

import hashlib

hashStore = []

password = input("Password to hash converter: ")
hashedPassword = hashlib.md5(password.encode())
print("Your hash is: ", hashedPassword.hexdigest())
reHash = hashedPassword
for i in range(10):
    reHash = hashlib.md5(reHash.hexdigest().encode('utf-8'))
    hashStore.append(reHash)
    print("Rehashed ",reHash.hexdigest())

推荐阅读