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())
The commented numbers in the above program denote the step numbers below :
- First of all, import the hashlib module.
- 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.
- 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.
- Finally, print out the hexadecimal equivalent of the encoded string using hexdigest() method.
The above program will print the below output :
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.
Similar tutorials :
- Python program to calculate total vowels in a string
- Python program to check if two strings are an anagram or not
- Python program to count the words and characters in a string
- Python program to swap the first and the last character of a string
- Python string ljust() method explanation with example
- Python program to find all numbers in a string