MD5 hash code generation in Python

Earlier we have seen a briefing about hash code in Python. Now we will see little more, especialy about MD5 hash code generation algorithm in Python’s hashlib module. To start with, let us see a simple example on how to use hashlib and it’s methods for MD5 hash generation.


import hashlib

# initialize a string
str = ""

# encode the string
encoded_str = str.encode()

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

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

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



The compact version of the above code:

>>> import hashlib
>>> hashlib.md5(b"").hexdigest()

Now let us see the other commonly used options available in md5 hashing.

Hash code in byte

As you have noticed, the above example returned the hash code as a hexadecimal value using the hexdigest() method. If you need to get the resultant hash code in byte value, then use the digest() method. Here is an example.

>>> import hashlib
>>> hashlib.md5(b"").digest()

Using update()

In the earlier examples we have created the hash object initialized with the encoded string or byte string. There is another way to append the byte string to the hash object using update() method. You can use the update() multiple times to append the byte string or any other byte date. This method comes in handy when you want to append date to the hash object based on multiple conditions. Here is an example.

import hashlib

# create a md5 hash object
hash_object = hashlib.md5()

# append the byte string

print("\n", hash_object.hexdigest(), "\n")




Leave your thoughts...

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