How to encode a string in MD5 using Python

In this tutorial, we will learn to encode a string using the MD5 algorithm in Python language. MD5 which is also known as the message-digest algorithm is used to produce a 128-bit hash value. This hashing algorithm is a one-way cryptographic function which takes input of any size and produces an output message digest of fixed size i.e. 128 bits.

MD5 hash using Python

Python consists of a library hashlib which is a common interface to various hashing and message digest algorithms. It includes the MD5 algorithm, secure hash algorithms like SHA1, SHA224, SHA256, and SHA512. In this tutorial, we will use this library to generate the message digest for the input string.

The code illustrated below takes an input string and the hash function encodes it. We get the byte equivalent of the string using the digest() function and finally, print it.

This tutorial will also help you: Secure Hash Algorithm (SHA) in Python

Python program to encode a string in MD5

#Python code to demonstrate MD5 algorithm
import hashlib
#input string string='codespeedy.com' 
#Encoding the input string using encode()
en=string.encode()
#passing the encoded string to MD5 hash function
h=hashlib.md5(en) 
#printing the digest value 
print("The byte equivalent is : ",h.digest())
Output:
The byte equivalent of the following is : b'\[email protected]\x18\x1cf|6\x07\x1eL"\xcc\x04AL'


We can also generate the hexadecimal equivalent of the encoded value using the code mentioned below. In this, we use hexdigest() to generate the hexadecimal value instead of digest().

# Python code to illustrate the working of MD 5 algorithm to generate hexadecimal equivalent
import hashlib 
#input string
string = "codespeedy.com"
# encoding the string using encode()  
en=string.encode()
# passing the encoded string to MD5
hex_result = hashlib.md5(en)
# printing the equivalent hexadecimal value 
print("The hexadecimal equivalent of hash is : ",hex_result.hexdigest())  
Output:
The hexadecimal equivalent of hash is : b16240181c667c36071e4c22cc04414c

You may also read:

Leave a Reply

Your email address will not be published. Required fields are marked *