python - 如何在 Python 中散列变量?

标签 python python-3.x hashlib

这个例子工作正常 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/

相关文章:

python - 线性回归 : How to find the distance between the points and the prediction line?

python - Seaborn 热图 - 颜色条标签字体大小

python - 为什么包含简单 while 循环的 for 循环只运行两次?而且很差

python - python中的异常传播

python - 如何使用 Python 查找 ISO 文件的 MD5 哈希值?

python - 使用盐在 SHA512 中进行散列? - Python

python - 快速获取视频文件唯一标识的方法

python - 迭代数据框并检查日期

Python 和 lxml : get sub-sub-element from given element

python - 如何防止BeautifulSoup网页崩溃?