Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix Unicode encode error using the hashlib module?

After multiple searches I have not been able to determine how to avoid an error stating: "Unicode-objects must be encoded before hashing" when using this code:

    pwdinput = input("Now enter a password:")     pwd = hashlib.sha1()     pwd.update(pwdinput)     pwd = pwd.hexdigest() 

How can I get past that error? How do you encode Unicode-objects?

like image 899
Nate Avatar asked Jul 13 '11 17:07

Nate


People also ask

How do I fix Unicode encode errors in Python?

The key to troubleshooting Unicode errors in Python is to know what types you have. Then, try these steps: If some variables are byte sequences instead of Unicode objects, convert them to Unicode objects with decode() / u” before handling them.

How do I resolve UnicodeEncodeError?

To fix UnicodeEncodeError: 'charmap' codec can't encode characters with Python, we can set the encodings argument when we open the file. to call open with the fname file name path and the encoding argument set to utf-8 to open the file at fname as a Unicode encoded file.

What is Hexdigest in Python?

hexdigest() : the digest is returned as a string object of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments.


1 Answers

pwdinput = input("Now enter a password:").encode('utf-8') # or whatever encoding you wish to use 

Assuming you're using Python 3, this will convert the Unicode string returned by input() into a bytes object encoded in UTF-8, or whatever encoding you wish to use. Previous versions of Python do have it as well, but their handling of Unicode vs. non-Unicode strings was a bit messy, whereas Python 3 has an explicit distinction between Unicode strings (str) and immutable sequences of bytes that may or may not represent ASCII characters (bytes).

http://docs.python.org/library/stdtypes.html#str.encode
http://docs.python.org/py3k/library/stdtypes.html#str.encode

like image 152
JAB Avatar answered Sep 19 '22 21:09

JAB