0

对于我为自己设计的编程练习,以及稍后在相当不安全的系统中使用,我正在尝试比较 MD5 哈希值。一种存储在纯文本文件中并由check_pw()函数提取,另一种是根据 CGI 表单中提交的密码创建的。md5_pw() 用于创建程序中的所有哈希。

出于某种原因,如果(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
4

2 回答 2

2

pair[1]可能有一个尾随换行符。尝试:

for line in f:
    line = line.rstrip()
    pair = line.split(":")
    # ...etc
于 2009-07-23T05:19:10.850 回答
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 散列)

于 2009-07-23T05:31:55.253 回答