在 Python 中比较 MD5
对于我为自己设计的编程练习,以及稍后在相当不安全的系统中使用,我尝试比较 MD5 哈希值。 一个存储在纯文本文件中并由 check_pw()
函数提取,另一个是根据 CGI 表单提交的密码创建的。 md5_pw(
) 用于创建程序中的所有哈希值。
由于某种原因,if (pair[1] == md5_pw(pw))
总是失败,即使我的程序在我的错误检查行:
print "这是文件中的密码:",pair[1],"
" print "这是您输入的 md5 密码:", md5_pw(pw), "
"
我哪里搞砸了?
代码:
def md5_pw(pw):
"""Returns the MD5 hex digest of the pw with addition."""
m = md5.new()
m.update("4hJ2Yq7qdHd9sdjFASh9"+pw)
return m.hexdigest()
def check_pw(user, pw, pwfile):
"""Returns True if the username and password match, False otherwise. pwfile is a xxx.txt format."""
f = open(pwfile)
for line in f:
pair = line.split(":")
print "this is the pw from the file: ", pair[1], "<br />"
print "this is the md5 pw you entered: ", md5_pw(pw), "<br />"
if (pair[0] == user):
print "user matched <br />"
if (pair[1] == md5_pw(pw)):
f.close()
return True
else:
f.close()
print "passmatch a failure"
return False
For a programming exercise I designed for myself, and for use in a pretty non-secure system later on, I'm trying to compare MD5 hashes. The one that is stored in a plain text file and is pulled out by the check_pw()
function and the one that is created from the submitted password from a CGI form. md5_pw(
) is used to create all the hashes in the program.
For some reason, if (pair[1] == md5_pw(pw))
always fails, even though my program prints out identical hashes in my error checking lines:
print "this is the pw from the file: ", pair[1], "<br />" print "this is the md5 pw you entered: ", md5_pw(pw), "<br />"
Where am I messing up?
Code:
def md5_pw(pw):
"""Returns the MD5 hex digest of the pw with addition."""
m = md5.new()
m.update("4hJ2Yq7qdHd9sdjFASh9"+pw)
return m.hexdigest()
def check_pw(user, pw, pwfile):
"""Returns True if the username and password match, False otherwise. pwfile is a xxx.txt format."""
f = open(pwfile)
for line in f:
pair = line.split(":")
print "this is the pw from the file: ", pair[1], "<br />"
print "this is the md5 pw you entered: ", md5_pw(pw), "<br />"
if (pair[0] == user):
print "user matched <br />"
if (pair[1] == md5_pw(pw)):
f.close()
return True
else:
f.close()
print "passmatch a failure"
return False
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
pair[1]
可能有一个尾随换行符。 尝试:Your
pair[1]
probably has a trailing newline. Try:我的猜测是文件加载/解析存在问题,很可能是由换行符引起的。 通过削减你的代码,我发现你的逻辑是合理的:(
“c317db7d54073ef5d345d6dd8b2c51e6”是“4hJ2Yq7qdHd9sdjFASh9testpw”的md5哈希值)
My guess is that there's an problem with the file loading/parsing, most likely caused by a newline character. By paring your code down, I was able to find that your logic was sound:
("c317db7d54073ef5d345d6dd8b2c51e6" is the md5 hash for "4hJ2Yq7qdHd9sdjFASh9testpw")