这个例子工作正常 example :
import hashlib
m = hashlib.md5()
m.update(b"Nobody inspects")
r= m.digest()
print(r)
现在,我想做同样的事情,但使用一个变量:var= "hash me this text, please"
。我怎样才能按照示例的相同逻辑来做到这一点?
最佳答案
hash.update()
method始终需要字节。
首先将unicode文本编码为字节;您将编码为的内容是应用程序的决定,但如果您只想做指纹文本,那么 UTF-8 是一个不错的选择:
m.update(var.encode('utf8'))
然而,当您不十分清楚时,您得到的异常是:
>>> import hashlib
>>> hashlib.md5().update('foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Unicode-objects must be encoded before hashing
如果您正在获取一个文件的哈希值,请改为以二进制模式打开该文件:
from functools import partial
hash = hashlib.md5()
with open(filename, 'rb') as binfile:
for chunk in iter(binfile, partial(binfile.read, 2048)):
hash.update(chunk)
print hash.hexdigest()
关于python - 如何在 Python 中散列变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24905062/