【问题标题】:How to hash an already hashed value for a given range?如何散列给定范围的已散列值?
【发布时间】:2019-06-04 13:02:26
【问题描述】:

我正在尝试设计一种一次性密码算法。我想从用户那里获取一个字符串输入,然后将其重复散列 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())

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

感谢您的任何帮助:)

【问题讨论】:

  • rehashreHash 是不同的变量。注意你的编码标准。您也永远不会启动循环(即i = 0)。这段代码应该在几个地方出错。您可能只想使用for 循环而不是启动while 循环:for _ in range(1, 10):

标签: python python-3.x cryptography md5 hashlib


【解决方案1】:
  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())

【讨论】:

  • 是的,谢谢!我不知道转换部分,今天学到了一些新东西。
  • for i in range(1,10): 只会循环 9 次。
  • 谢谢,已修复。
【解决方案2】:

改用 for 循环,用初始哈希初始化 hashStore,并在每个循环中重新哈希最后一个哈希哈希 (hashStore[-1]):

import hashlib

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

hashStore= [hashedPassword]
for _ in range(1,100):
    reHash = hashlib.md5(hashStore[-1].hexdigest().encode('utf-8'))
    hashStore.append(reHash)
    print("Rehashed ",reHash.hexdigest())

【讨论】:

    猜你喜欢
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 2014-05-19
    • 2017-10-13
    • 2011-10-06
    • 2010-09-26
    • 1970-01-01
    相关资源
    最近更新 更多