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', 
'blake2s'}
>>>

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")

Result:

40c6b5a9034897b778fe7c6c69521f7ee4b9f9b607af23646f325d1abcb989a33ca469a26aa3f697cc526e1bc1a5aa9986cb0378c1f53f67f83eae0207e91f06

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

More on hash codes

Reference


Leave your thoughts...

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