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

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


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!


Since you are encoding simple strings I deduce that you are running Python 3 where all strings are unicode objects, you have two options:

  1. Provide an encoding for the strings, e.g.: "Nobody inspects".encode('utf-8')
  2. Use binary strings as shown in the manuals:

    m.update(b"Nobody inspects")m.update(b" the spammish repetition")

The reason for the differing behaviour in the script to the shell is that the script stops on the error whereas in the shell the last line is a separate command but still not doing what you wish it to because of the previous error.


It's not working in the REPL. It's hashed nothing, since you've passed it nothing valid to hash. Try encoding first.

3>> hashlib.md5().digest()b'\xd4\x1d\x8c\xd9\x8f\x00\xb2\x04\xe9\x80\t\x98\xec\xf8B~'3>> a = hashlib.md5()3>> a.update('hi'.encode('utf-8'))3>> a.digest()b'I\xf6\x8a\\\x84\x93\xec,\x0b\xf4\x89\x82\x1c!\xfc;'