Hash code (hashing) in Python

Python has an abundant support for several hash code algorithms through the library module hashlib. You can use the constant attribute hashlib.algorithms_available to get the list of all available hash algorithms in your installed version of Python environment.

>>> import hashlib 
>>> hashlib.algorithms_available
{'md5', 'sha224', 'sha1', 'ripemd160', 'sha3_384', 
'blake2b512', 'md4', 'sha256', 'shake_128', 'sha512', 
'sha3_224', 'shake_256', 'whirlpool', 'sha384', 
'blake2s256', 'blake2b', 'sha3_512', 'md5-sha1', 
'sha3_256', 'blake2s'}

You can see there are twenty algorithms available in my environment, i.e. Python 3.7.3. However, not all of these algorithms are supported by hashlib module on all platforms. In order to get the list of the algorithms which are guaranteed to be supported by all the platforms, use the constant hashlib.algorithms_guaranteed. Here is the list of guaranteed algorithms in my environment.

>>> import hashlib
>>> hashlib.algorithms_guaranteed
{'md5', 'sha224', 'sha512', 'sha1', 'sha3_224', 
'shake_256', 'sha384', 'sha3_384', 'blake2b', 
'sha3_512', 'sha256', 'shake_128', 'sha3_256', 

As you can see, algorithms_guaranteed will be a sub set of algorithms_available.

Now we will see how to to use the library to generate hash codes. Here is an example generating blake2b hash for a given string.

import hashlib

# initialize a string
str = "www.MyTecBits.com"

# encode the string
encoded_str = str.encode()

# create a hash object initialized with the encoded string
hash_obj = hashlib.blake2b(encoded_str)

# convert the hash object to a hexadecimal value
hexa_value = hash_obj.hexdigest()

# print
print("\n", hexa_value, "\n")



In the coming days, I will add more articles on hashing in Python.

More on hash codes


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.