【问题标题】:Compare result from hexdigest() to a string将 hexdigest() 的结果与字符串进行比较
【发布时间】:2011-04-04 17:44:19
【问题描述】:

我有一个生成的 MD5 散列,我想将它与字符串中的另一个 MD5 散列进行比较。下面的陈述是错误的,即使它们在您打印时看起来相同并且应该是正确的。

hashlib.md5("foo").hexdigest() == "acbd18db4cc2f85cedef654fccc4a4d8"

Google 告诉我应该对来自hexdigest() 的结果进行编码,因为它不返回字符串。但是,下面的代码似乎也不起作用。

hashlib.md5("foo").hexdigest().encode("utf-8") == "foo".encode("utf-8")

【问题讨论】:

    标签: python string-comparison python-2.x hashlib


    【解决方案1】:

    使用 == 进行哈希比较可能存在安全漏洞。

    https://groups.google.com/forum/?fromgroups=#!topic/keyczar-discuss/VXHsoJSLKhM

    攻击者可能会寻找时间差异并有效地遍历密钥空间并找到一个可以通过相等性测试的值。

    【讨论】:

    【解决方案2】:

    hexdigest returns a string。您的第一条语句在 python-2.x 中返回 True

    在 python-3.x 中,您需要将参数编码为 md5 函数,在这种情况下,相等性也是 True。如果没有编码,它会引发TypeError

    【讨论】:

      【解决方案3】:

      Python 2.7,.hexdigest() 确实返回一个 str

      >>> hashlib.md5("foo").hexdigest() == "acbd18db4cc2f85cedef654fccc4a4d8"
      True
      >>> type(hashlib.md5("foo").hexdigest())
      <type 'str'>
      

      Python 3.1

      .md5() 不采用 unicode(“foo”是),因此需要将其编码为字节流。

      >>> hashlib.md5("foo").hexdigest()
      Traceback (most recent call last):
        File "<pyshell#1>", line 1, in <module>
          hashlib.md5("foo").hexdigest()
      TypeError: Unicode-objects must be encoded before hashing
      
      >>> hashlib.md5("foo".encode("utf8")).hexdigest()
      'acbd18db4cc2f85cedef654fccc4a4d8'
      
      >>> hashlib.md5("foo".encode("utf8")).hexdigest() == 'acbd18db4cc2f85cedef654fccc4a4d8'
      True
      

      【讨论】:

      • 您的最后一段代码运行良好。不知何故,在我的 AppEngine 开发服务器上进行测试时,我没有收到错误消息。我应该在 python 控制台中测试它。我很抱歉,下次会这样做。
      猜你喜欢
      • 2022-01-25
      • 1970-01-01
      • 2016-08-01
      • 2012-05-12
      • 1970-01-01
      • 2012-10-06
      • 2019-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多