Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
The Python "TypeError: Strings must be encoded before hashing" occurs when we
pass a string to a hashing algorithm. To solve the error, use the encode()
method to encode the string to a bytes object, e.g. my_str.encode('utf-8')
.
Here is an example of how the error occurs.
import hashlib my_str = 'some long string' # ⛔️ TypeError: Strings must be encoded before hashing my_hash = hashlib.sha256(my_str).hexdigest()
We used sha256()
to create a SHA-256 hash object and passed a string to it,
which caused the error.
To solve the error, pass a bytes
object to the method instead, e.g.
my_str.encode('utf-8')
.
import hashlib my_str = 'some long string' # ✅ encode str to bytes my_hash = hashlib.sha256(my_str.encode('utf-8')).hexdigest() # 👇️ 884b1cd6959c81bc443b50a6cb38813ecb21e20d05690aa2109014e5f8ecb8f6 print(my_hash)
The str.encode
method returns an encoded version of the string as a bytes object. The default
encoding is utf-8
.
If you have a string literal, and not a string stored in a variable, you can
prefix the string with b
to encode it to a bytes object.
import hashlib my_hash = hashlib.sha256(b'some long string').hexdigest() # 👇️ 884b1cd6959c81bc443b50a6cb38813ecb21e20d05690aa2109014e5f8ecb8f6 print(my_hash)
b
achieves the same result as calling the encode()
method on it, but can only be used if you have a string literal, and not a string stored in a variable.You can get the digest of the concatenation of the data fed to the hash object
by using the digest()
or hexdigest()
methods.
If you aren't sure what type of object a variable stores, use the built-in
type()
class.
my_bytes = 'hello'.encode('utf-8') print(type(my_bytes)) # 👉️ <class 'bytes'> print(isinstance(my_bytes, bytes)) # 👉️ True my_str = 'hello' print(type(my_str)) # 👉️ <class 'str'> print(isinstance(my_str, str)) # 👉️ True
The type class returns the type of an object.
The isinstance
function returns True
if the passed in object is an instance or a subclass of
the passed in class.