Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
974 views
in Technique[技术] by (71.8m points)

python - hashlib.md5() TypeError: Unicode-objects must be encoded before hashing

I am new to coding and have ran into a problem trying to encode a string.

>>> import hashlib
>>> a = hashlib.md5()
>>> a.update('hi')
Traceback (most recent call last):
  File "<pyshell#22>", line 1, in <module>
    a.update('hi')
TypeError: Unicode-objects must be encoded before hashing
>>> a.digest()
b'xd4x1dx8cxd9x8fx00xb2x04xe9x80x98xecxf8B~'

Is (a) now considered to be encoded?

Second question: When I run the same code above in a script I get this error:

import hashlib
a = hashlib.md5()
a.update('hi')
a.digest()

Traceback (most recent call last): File "C:/Users/User/Desktop/Logger/Encoding practice.py", line 3, in a.update('hi') TypeError: Unicode-objects must be encoded before hashing

Why is the code working in the shell and not the script? I am working with Windows and Python 3.4

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The solution I've found is to simply encode the data right away in the line where you're hashing it:

hashlib.sha256("a".encode('utf-8')).hexdigest()

It worked for me, hope it helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...