Published on

Create MD5 Hash of a string in Python

Create MD5 Hash of a string in Python

MD5 is (atleast when it was created) a standardized 1-way function that takes in data input of any form and maps it to a fixed-size output string, irrespective of the size of the input string.

Though it is used as a cryptographic hash function, it has been found to suffer from a lot of vulnerabilities.

A salt is a randomly generated string of characters that is used as an additional input to a one-way hash function. Salts are used to protect against dictionary attacks and rainbow table attacks.

The MD5 hash with salt is generated by concatenating the salt to the password and then hashing the resulting string. The salt is then appended to the generated hash to form the complete hash. This complete hash is then stored in the database. When a user attempts to login, the salt is retrieved from the database and used to generate a hash from the provided password. The generated hash is then compared to the hash stored in the database. If the two hashes match, the user is authenticated.

We can create an MD5 hash of a string in Python without using an hash as well. In this article we will create a hash by using a salt.

The method below is for creating it in Python i.e., on the server side.

MD5 hash with salt in Python

MD5 hash can be created using the python's default module hashlib. There are many more hash functions defined in the hashlib library.

The process of creating an MD5 hash in python is very simple. First import hashlib, then encode your string that you want to hash i.e., converts the string into the byte equivalent using encode(), then pass it through the hashlib.md5() function. Here, we also concat the salt. We print the hexdigest value of the hash m, which is the hexadecimal equivalent encoded string.

Working code example-

import hashlib

text = 'Hello!'
salt = '80zzm081sr@nd0m'

m = hashlib.md5(text.encode('UTF-8') + salt.encode('UTF-8'))

Output of the above code-


The value you see here ef26fcd3896d184b4eae38725d4c934e is the MD5 hash of the string Hello! with salt 80zzm081sr@nd0m.

The functions used in the above code-

  • encode() : Converts the string into bytes to be acceptable by hash function.
  • hexdigest() : Returns the encoded data in hexadecimal format.

As you see, the MD5 hash of a string with salt using Python is as simple as this code.

In case you are looking to create MD5 hash of a file or a blob check out this article.

NOTE : Please do not use this to hash passwords and store it in your databases, prefer SHA-256 or SHA-512 or other superior cryptographic hash functions for the same.

I'm glad that you found the content useful. Happy Coding.