为什么文件中某个单词的md5散列与字符串的散列不匹配? [英] Why md5 hash of a word from a file doesn't match the hash of a string?

查看:204
本文介绍了为什么文件中某个单词的md5散列与字符串的散列不匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个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()会失败。在这种情况下,只需要:

  line.encode('utf_8')。rstrip('\r\\\
' )

如果文件在Unix上以 text code> \ r (回车符)可能会保留(不是Windows上的问题)。

(和 rstrip 不会删除'\r\\\
'字符串,但每个 \r 或/和 >

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:

if hashlib.md5(b"string").hexdigest() == "b45cffe084dd3d20d928bee85e7b0f21":
    print("Equal!")

But when I read the words line by line from a file, the hash of the word is different. The code looks like this:

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)

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.

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

if the file is open in text mode on Unix, possible \r (carriage return) could remain (not a problem on windows)

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

这篇关于为什么文件中某个单词的md5散列与字符串的散列不匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆