How to find the md5 hash of a string in python

md5 hash :

Hash calculation is one of the most used cryptographic function. Hash is used to checking the checksum of a file, password verification, fingerprint verification, build caches of large data sets etc.

Hash function returns a fixed sized string. Think about comparing two files. It will take a lot of time to compare both files if the size is huge. Instead, we can use a hash function to create the hash for each file and compare these values easily.

There are a lot of cryptographic hash functions like MD5, SHA-1, SHA-256 etc. You can check this Wikipedia article to learn more on these names.

This tutorial is on MD5 hash function that is used to produce a 128 bit hash value. MD5 is not widely used these days as it has few security issues.

In python, you don’t have to write much code to implement the md5 function. Python has one module called hashlib that is packed with a lot of hash functions.

So, in this tutorial, we will use the hashlib module to find out the MD5 value of a string.

Let’s have a look :

Python program :

#1
import hashlib

#2
given_str = b"Hello world"
given_str_2 = b"Hello world !!"

#3
md5_value = hashlib.md5(given_str)
md5_value_2 = hashlib.md5(given_str_2)

#4
print(md5_value.hexdigest())
print(md5_value_2.hexdigest())

Explanation :

The commented numbers in the above program denote the step numbers below :

  1. First of all, import the hashlib module.

  2. We have two strings with its byte representation: given_str and given_str_2. Both of these strings are in byte format as the md5 function takes the only byte as a parameter.

  3. Find the md5 value of the byte strings and store them in md5_value and md5_value_2 variables. We are using hashlib.md5() function to find out the md5 of the strings.

  4. Finally, print out the hexadecimal equivalent of the encoded string using hexdigest() method.

The above program will print the below output :

3e25960a79dbc69b674cd4ec67a72c62
10f73d16d32cf89e1f7cab7589be965b

You can see that both values are different. You can try to run the program multiple times and it will produce the same output for the same string. Using these hex values, you can easily compare two large strings. python find md5 string

Similar tutorials :