Python MD5 Hashing Examples

MD5 is a hashing algorithm that is used to create unique value for a given data or string. The MD5 is a non-reversible and one-way function. Python provides a function in order to calculate MD5 values and work with them easily. The MD5 hash function is provided via the hashlib module which is provided by default with Python.

The hashlib Module MD5 Methods

The hashlib is created to provide hash and cryptography related methods inPython. In order to calculate MD5 hashlib provides following methods.

  • md5() calculates and returns the MD5 hash of the provided data, string etc.
  • digest() prints the encoede data in byte format or byte type.
  • hexdigest() returns the encoede data in hexadecimal format.

Calculate MD5 For Text or String

The hashlib module provides the md5() method in order to calculate the MD5 hash of the provided data. The data should be formatted as byte type but a text or string can be easily converted to the byte. In the following example, we will calculate MD5 of the string “I like“. We will put the letter “b” before the string. The hexdigest() method of the retuned object is used to print MD5 value in hexadecimal format.

import hashlib

md5 = hashlib.md5(b'I like')

print("The Hash Value is ",md5.hexdigest())

Calculate MD5 For Interactive User Input

The user input is important where usernames or passwords generally input by users. As a security mechanism, the provided password can be stored as an MD5 hash. The input() method is used to get input and it can be converted into a byte and its hash value is calculated with the md5() method.

import hashlib

password = input("Please type password")

md5 = hashlib.md5(byte(password))

print("The Hash Value of the password is ",md5.hexdigest())

Calculate MD5 By Encoding

As the md5() method requires byte type we can encode the specified string type into the byte with the encoding. First we will define the string we want to calculate MD5 hash.

import hashlib

sentence = 
"I like"

md5 = hashlib.md5(sentence.encode())

print("The Hash Value of the password is ",md5.hexdigest())

Leave a Comment