为什么文件中某个单词的md5散列与字符串的散列不匹配? [英] Why md5 hash of a word from a file doesn't match the hash of a string?
问题描述
我试图创建一个python程序,它可以读取字典中的单词,创建一个md5散列并将其与给定的散列进行比较。
当我试图比较两个没有从文件中读取的单词哈希值时,一切正常。
if hashlib.md5(bstring)。hexdigest()==b45cffe084dd3d20d928bee85e7b0f21:
print(Equal!)
但是当我从文件中逐行读取单词时,单词的散列是不同的。代码如下所示:
f = open('short.txt','r')
stringHash ='b45cffe084dd3d20d928bee85e7b0f21'
for line in f:
if stringHash == hashlib.md5(line.encode('utf_8'))。hexdigest():
print(Found it!Password:%s%line)
帮助和解释。
逐行文件迭代器产生整行包括行结束符。
>在您的代码中,您将包含行的终止符。
行。 encode('utf_8').rstrip()
会产生正确的结果。
$ b
rstrip()$如果你的字符串用空格结束(特意),c $ c>会失败。在这种情况下,只需要:
line.encode('utf_8')。rstrip('\r\\\
' )
如果文件在Unix上以 text code> \ r (回车符)可能会保留(不是Windows上的问题)。
(和 I'm trying to create a python program that would read words from a dictionary, create a md5 hash and compare it to a given hash. Everything works fine when I try to compare two hashes of words that haven't been read from a file: But when I read the words line by line from a file, the hash of the word is different. The code looks like this: Thanks for any help and explanation. line-by-line file iterator yields the whole line including line terminators. In your code, you're including the line terminator of the line. if the file is open in text mode on Unix, possible (and 这篇关于为什么文件中某个单词的md5散列与字符串的散列不匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! rstrip
不会删除'\r\\\
'字符串,但每个 \r
或/和 >
if hashlib.md5(b"string").hexdigest() == "b45cffe084dd3d20d928bee85e7b0f21":
print("Equal!")
f = open('short.txt', 'r')
stringHash = 'b45cffe084dd3d20d928bee85e7b0f21'
for line in f:
if stringHash == hashlib.md5(line.encode('utf_8')).hexdigest():
print("Found it! Password: %s" % line)
line.encode('utf_8').rstrip()
will yield the correct result.rstrip()
will fail if your string ends (purposedly) with spaces. In that case, just do:line.encode('utf_8').rstrip('\r\n')
\r
(carriage return) could remain (not a problem on windows)rstrip
does not remove the '\r\n' string, but each \r
or/and n
contained at the end of the line, it's not like str.split
)