将hexdigest()的结果与字符串进行比较 [英] Compare result from hexdigest() to a string

查看:145
本文介绍了将hexdigest()的结果与字符串进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生成的MD5-hash,我想将其与字符串中的另一个MD5-hash进行比较.即使在打印时它们看起来一样,下面的语句也是假的.

I've got a generated MD5-hash, which I would like to compare to another MD5-hash from a string. The statement below is false, even though they look the same when you print them and should be true.

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

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

Google told me that I should encode the result from hexdigest(), since it doesn't return a string. However, the code below doesn't seem to work either.

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

推荐答案

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

Python 2.7, .hexdigest() does return a str

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

Python 3.1

Python 3.1

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

.md5() doesn't take a unicode (which "foo" is), so that needs to be encoded to a byte stream.

>>> 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

这篇关于将hexdigest()的结果与字符串进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆