【问题标题】:Comparing MD5s in Python比较 Python 中的 MD5
【发布时间】:2009-07-23 05:14:31
【问题描述】:

对于我为自己设计的编程练习,以及稍后在相当不安全的系统中使用,我正在尝试比较 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

【问题讨论】:

    标签: python md5


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢!我不知道迭代器也会返回换行符......啊,Python!
    【解决方案2】:

    我的猜测是文件加载/解析存在问题,很可能是由换行符引起的。通过削减你的代码,我发现你的逻辑是正确的:

    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 散列)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-20
      • 1970-01-01
      • 2016-01-08
      相关资源
      最近更新 更多