如何在Python中散列变量?

5 python hashlib python-3.x

这个例子正常工作例如:

import hashlib
m = hashlib.md5()
m.update(b"Nobody inspects")
r= m.digest()
print(r)
Run Code Online (Sandbox Code Playgroud)

现在,我想用变量做同样的事情:var= "hash me this text, please".我怎么能按照例子的相同逻辑做到这一点?

Mar*_*ers 9

hash.update()方法总是需要字节.

首先将unicode文本编码为字节; 你编码是一个应用程序决定,但如果你想做的只是指纹文本,那么UTF-8是一个很好的选择:

m.update(var.encode('utf8')) 
Run Code Online (Sandbox Code Playgroud)

但是,当你不这样做时,你得到的例外很明显:

>>> 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
Run Code Online (Sandbox Code Playgroud)

如果要获取文件的哈希值,请以二进制模式打开文件:

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()
Run Code Online (Sandbox Code Playgroud)

  • @begueradj:是的,它可以采取任何适合Python的东西.如果您正在读取文本文件,则可以多次调用`.digest()`,每次都使用下一个块.循环遍历文件以获取行,将每行传递给`.digest()`,并在文件完成后获取摘要. (2认同)
  • @begueradj:或者您可以在*binary*模式下打开文件,您不必再次编码. (2认同)