2009-07-23 42 views
0

对于我为自己设计的编程练习,以及稍后在非常不安全的系统中使用,我试图比较MD5哈希值。一个以纯文本文件存储的文件,由check_pw()函数和CGI表单提交的密码创建的函数提取。 md5_pw()用于在程序中创建所有哈希。在Python中比较MD5s

出于某种原因,如果(pair[1] == md5_pw(pw))总是失败,即使我的程序打印出我的错误检查线路相同的哈希值:

print "this is the pw from the file: ", pair[1], "<br />" 
    print "this is the md5 pw you entered: ", md5_pw(pw), "<br />" 

我在哪里搞乱?

代码:

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 

回答

2

pair[1]可能有一个结尾的新行。尝试:

for line in f: 
    line = line.rstrip() 
    pair = line.split(":") 
    # ...etc 
+0

非常感谢您!我没有意识到迭代器也会返回新行......啊,Python! – Isaac 2009-07-23 05:27:42

1

我的猜测是,有与文件加载/分析,很有可能是由一个换行符引起的问题。通过削减你的代码的时候,我能找到你的逻辑是合理的:

def md5_pw(pw): 
    m = md5.new() 
    m.update("4hJ2Yq7qdHd9sdjFASh9"+pw) 
    return m.hexdigest() 

def check_pw(pw): 
    pair = ("c317db7d54073ef5d345d6dd8b2c51e6") 
    if (pair == md5_pw(pw)): 
     return True 
    else: 
     return False 

>>> import md5 
>>> check_pw('fakepw') 
False 
>>> check_pw('testpw') 
True 

(“c317db7d54073ef5d345d6dd8b2c51e6”是“4hJ2Yq7qdHd9sdjFASh9testpw” MD5哈希)