Generating an MD5 hash

The MD5 hash is one of the most commonly used hashes within web applications due to their ease of use and the speed at which they are hashed. The MD5 hash was invented in 1991 to replace the previous version, MD4, and it is still used to this day.

Getting ready

For this script, we will only need the hashlib module.

How to do it…

Generating an MD5 hash within Python is extremely simple, due to the nature of the module we can import. We need to define the module to import and then decide which string we want to hash. We should hard code this into the script, but this means the script would have to be modified each time a new string has to be hashed.

Instead, we use the raw_input feature in Python to ask the user for a string:

import hashlib
message = raw_input("Enter the string you would like to hash: ")
md5 = hashlib.md5(message.encode())
print (md5.hexdigest())

How it works…

The hashlib module does the bulk of the work for us behind the scenes. Hashlib is a giant library that enables users to hash MD5, SHA1, SHA256, and SHA512, among others extremely quickly and easily. This is the reasoning for using this module.

We first import the module using the standard method:

import hashlib

We then need the string that we wish to MD5 encode. As mentioned earlier, this could be hard-coded into the script but it's not extremely practical. The way around this is to ask for the input from the user by using the raw_input feature. This can be achieved by:

message = raw_input("Enter what you wish to ask the user here: ")

Once we have the input, we can continue to encode the string using hashlib's built-in functions. For this, we simply call the .encode() function after defining the string we are going to be using:

md5 = hashlib.md5(message.encode())

Finally, we can print the output of the string that uses the .hexdigest() function. If we do not use hexdigest, the hex representation of each byte will be printed.

Here is an example of the script in full swing:

Enter the string you would like to hash: pythonrules
048c0fc556088fabc53b76519bfb636e
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.54.255