Thursday, September 6, 2018

How do you correct, 'TypeError: Unicode-objects must be encoded before hashing'?

When you import 'hashlib' in Python and try to run the following statement you would get an error as shown:
----------
>>> print (hashlib.sha256("Hello World").hexdigest())
Traceback (most recent call last):
  File "", line 1, in
    print (hashlib.sha256("Hello World").hexdigest())
TypeError: Unicode-objects must be encoded before hashing
-----------

There are two ways you can correct this error:
---------
>>> print (hashlib.sha256(b"Hello World").hexdigest())
a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e
------------
>>> print (hashlib.sha256("Hello World".encode('utf-8')).hexdigest())
a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e
---------------------------
Python version used:
Python 3.6.6 (v3.6.6:4cf1f54eb7, Jun 27 2018, 03:37:03) [MSC v.1900 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.

No comments: