Python 从列表或文本创建 md5 哈希

Python creating md5 hashes from a list or text

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

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
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())

Output

1a1dc91c907325c69271ddf0c944bc72
827ccb0eea8a706c4c34a16891f84e7b
5f4dcc3b5aa765d61d8327deb882cf99

你必须移动这个:

result = hashlib.md5()

在你的循环中,所以它每次都会为每一行重新初始化。最终代码可能如下所示:

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

您需要为每一行独立的 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())