Change language

MD5 hash in Python

There are many hash functions defined in the " hashlib " library in python. 
This article is about the explanation and operation of the MD5 hash.

MD5 Hash

This hash function takes a sequence of bytes and returns 128- a bit hash value which is commonly used to check data integrity but has security concerns.

Related Functions:

  • encode (): converts the string to bytes so that it is acceptable for the hash function.
  • digest (): returns encoded data in byte format.
  • hexdigest (): returns encoded data in hexadecimal format.

The code below demonstrates an MD5 hash that takes bytes and is output as bytes.

# Python 3 demo code
# MD5 work (byte - byte)

< code class = "undefined spaces">  

import hashlib

# encoding Python.Engineering using md5 hash
# function

result = hashlib.md5 (b ’GeeksforGeeks’ )

# prints the equivalent byte value.

print ( "The byte equivalent of hash is:" , end = " ")

print (result.digest ())


 The byte equivalent of hash is: b’xf1xe0ix ~ xcetSx1dx11% Yx94  hq’ 

Explanation: The above code occupies a byte and can be received by a hash function. The md5 hash function encodes it, and then digest () outputs the encoded byte equivalent string.

The code below shows how to take a string as input and output hexadecimal equivalent of the encoded value.

# Python 3 demo code
# working with MD5 (string - hexadecimal)


import hashlib

# initialization string

str = "GeeksforGeeks"

# encoding Python.Engineering using encode ()
# then submit to md5 ()

result = hashlib.md5 ( str . encode ())

# Prints the equivalent hexadecimal value.

print ( "The hexadecimal equivalent of hash is:" , end = "")

print (result.hexdigest ())


 The hexadecimal equivalent of hash is: f1e069787ece74531d112559945c6871 

Explanation: The above code takes a string and converts it to byte equivalent using encode () so that it can be when nat hash function. The md5 hash function encodes it and then uses hexdigest () to output the hexadecimal equivalent encoded string.


Learn programming in R: courses


Best Python online courses for 2022


Best laptop for Fortnite


Best laptop for Excel


Best laptop for Solidworks


Best laptop for Roblox


Best computer for crypto mining


Best laptop for Sims 4


Latest questions


psycopg2: insert multiple rows with one query

12 answers


How to convert Nonetype to int or string?

12 answers


How to specify multiple return types using type-hints

12 answers


Javascript Error: IPython is not defined in JupyterLab

12 answers



Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method