【问题标题】:Python creating md5 hashes from a list or textPython 从列表或文本创建 md5 哈希
【发布时间】:2020-05-21 10:08:41
【问题描述】:

当它是脚本中的字符串时,它会正确生成它:

result = hashlib.md5(b"12345")
print(result.hexdigest())

这是: 827ccb0eea8a706c4c34a16891f84e7b 应该是,但是当从列表或文本中读取单词时,它不会给出正确的 md5 哈希值。我试图剥离“\n”,但它没有用。我应该怎么办?如果你要从文本中生成 md5 哈希,你会怎么做?

import hashlib

result = hashlib.md5()

with open("text.txt", mode="r", encoding="utf-8") as f:
    for line in f:
        line.strip("\n")

        result.update(line.encode())
        result_md5 = result.hexdigest()


        print(result.hexdigest())

输出为:4528e6a7bb9341c36c425faf40ef32c3

b6cef2a8d7cd668164035a08af6eab17

f44b0df2bb9752914ceac919ae4ca5e5

文本文件:

pass
12345
password

预期输出是:

1a1dc91c907325c69271ddf0c944bc72
827ccb0eea8a706c4c34a16891f84e7b
5f4dcc3b5aa765d61d8327deb882cf99

【问题讨论】:

  • 在问题中将示例代码、示例文本文件、结果和预期结果显示为格式正确的文本。
  • 我试过了。我希望现在更清楚了。

标签: python md5 hashlib


【解决方案1】:

您希望每行独立的 MD5 散列。

import hashlib

with open("text.txt", mode="r", encoding="utf-8") as f:
    for line in f:
        line = line.rstrip("\r\n")
        result = hashlib.md5(line.encode())
        print(result.hexdigest())

【讨论】:

    【解决方案2】:
    import hashlib
    
    with open("text.txt", "r") as f:
        temp = f.read().splitlines()
        for each_element in temp:
            result = hashlib.md5(each_element.encode("utf-8"))
            print(result.hexdigest())
    

    输出

    1a1dc91c907325c69271ddf0c944bc72
    827ccb0eea8a706c4c34a16891f84e7b
    5f4dcc3b5aa765d61d8327deb882cf99
    

    【讨论】:

      【解决方案3】:

      你必须移动这个:

      result = hashlib.md5()
      

      在您的循环中,因此每次新行都会重新初始化。最终代码可能如下所示:

      with open("text.txt") as f:
          for line in f:
              print(hashlib.md5(line.strip().encode()).hexdigest())
      

      【讨论】:

      • 获取TypeError: Unicode-objects must be encoded before hashing
      猜你喜欢
      • 2011-01-10
      • 2017-07-26
      • 2017-05-04
      • 2021-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      相关资源
      最近更新 更多