Python hashlib 没有为 md5 生成正确的散列

Python hashlib not producing the correct hash for md5

我正在开发一个 python 小程序,该程序本质上将使用 word 文件强制执行 md5 哈希。该程序获取您的哈希值,然后您可以 select 一个文件用作单词列表。然后它将在文件中逐行检查并生成一个 md5 哈希版本以检查您输入的版本。如果它们匹配,那么它会告诉您产生该散列的单词。问题在于,当程序将行转换为散列时,它不会生成正确可识别的 md5 散列。例如,它说测试的 md5 哈希是 d8e8fca2dc0f896fd7cb4cb0031ba249。我尝试了多种编码文本的方式等等,但找不到正确的答案。我做错了什么?

import hashlib

mainhash = raw_input("What hash would you like to try and break?")
filename = raw_input("What file would you like to use?")
times = 0


if filename == "":
    print "A list file is required."
    exit()

f = open(filename)
for line in iter(f):
    times = times + 1
    word = line
    line = hashlib.md5(line.encode("utf")).hexdigest()
    print line
    if line == mainhash:
        print "Matching Hash found. Word is:"
        print word
        print times
        exit()

f.close()
print "Sorry no match was found. Please try a different word file or make sure the hash is md5."
print times

line 在行尾包含换行符。替换:

line = hashlib.md5(line.encode("utf")).hexdigest()

与:

line = hashlib.md5(line.encode("utf").strip()).hexdigest()

即使是字符串末尾的单个换行符也会完全改变散列。