How to hash a variable in Python?

有些话、适合烂在心里 提交于 2019-12-10 14:58:27

问题


This example works fine example:

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

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 ?


回答1:


The hash.update() method requires bytes, always.

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



回答2:


Try this. Hope it helps. The variable var has to be utf-8 encoded. If you type in a string i.e. "Donald Duck", the var variable will be b'Donald Duck'. You can then hash the string with hexdigest()

#!/usr/bin/python3
import hashlib
var = input('Input string: ').encode('utf-8')
hashed_var = hashlib.md5(var).hexdigest()
print(hashed_var)



回答3:


I had the same issue as the OP. I couldn't get either of the previous answers to work for me for some reason, but a combination of both helped come to this solution.

I was originally hashing a string like this;

str = hashlib.sha256(b'hash this text')
text_hashed = str.hexdigest()
print(text_hashed)

Result;d3dba6081b7f171ec5fa4687182b269c0b46e77a78611ad268182d8a8c245b40

My solution to hash a variable;

text = 'hash this text'
str = hashlib.sha256(text.encode('utf-8'))
text_hashed = str.hexdigest()
print(text_hashed)

Result; d3dba6081b7f171ec5fa4687182b269c0b46e77a78611ad268182d8a8c245b40



来源:https://stackoverflow.com/questions/24905062/how-to-hash-a-variable-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!