如何在Python中对变量进行哈希处理? [英] How to hash a variable in Python?

查看:183
本文介绍了如何在Python中对变量进行哈希处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此示例可以很好地运行示例:

This example works fine example:

import hashlib
m = hashlib.md5()
m.update(b"Nobody inspects")
r= m.digest()
print(r)

现在,我想做同样的事情,但是要有一个变量:var= "hash me this text, please".我如何按照示例中的相同逻辑进行操作?

Now, I want to do the same thing but with a variable: var= "hash me this text, please". How could I do it following the same logic of the example ?

推荐答案

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

Encode unicode text to bytes first; what you encode to is a application decision, but if all you want to do is fingerprint text for then UTF-8 is a great choice:

m.update(var.encode('utf8')) 

但是,很明显,当您不在时会遇到异常:

The exception you get when you don't is quite clear however:

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

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

If you are getting the hash of a file, open the file in binary mode instead:

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中对变量进行哈希处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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