MD5 hash in Python

Python Methods and Functions

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.