Hashing

by Arpan pandeyJuly 23, 2021

Let's go hashing... Don't know what is hashing? Cling On for first we discover hashing and then we go about hashing real stuff using code.

What is hashing?

Going by definition, hashing is...

Hashing is the process of converting a given key into another value. A hash function is used to generate the new value according to a mathematical algorithm. The result of a hash function is known as a hash value or simply, a hash.

The Definition

So to clarify, hashing is just a technique used to create a seemingly random value from a bunch of data so that it is the same every time we put the same data in. All of this is done through a mathematical algorithm. These algorithms are called hashing algorithms.

What makes a good hashing algorithm?

A good hashing function has the following:

  • Produces a unique value for unique input.
  • It is one-way.
  • Can't be reverse engineered.
  • It should be fast to compute.
  • A tiny change should be able to considerably change the hash.

Bring in the libraries.

We only need the built-in hashlib module. This module can help us do all of the tasks related to hashing in python.


import hashlib

Now, we go ahead and encode the text that we have into bytes.

Just using the .encode() after the string to convert the text into binary and store it into a variable.


message = "Hi! This is something to encode.".encode()

MD5 Algorithm:

Now, we are going to use the MD5 algorithm to get an MD5 hash.


print("MD5:", hashlib.md5(message).hexdigest())

SHA2 Algorithms:

Now, we are going to use the SHA2 algorithm to get a SHA256 and a SHA512 hash.


print("SHA-256:", hashlib.sha256(message).hexdigest())

print("SHA-512:", hashlib.sha512(message).hexdigest())

SHA3 Algorithms:

Now, we are going to use the SHA3 algorithm to get a SHA3-256 and a SHA3-512 hash.


print("MD5:", hashlib.md5(message).hexdigest())

Blake2 Algorithms:

Now, we are going to use the Blake2 algorithm to get a Blake2s(or 256 bits) and a Blake2b(or 512 bits) hash.


# 256-bit Blake2 hash.
print("BLAKE2c:", hashlib.blake2s(message).hexdigest())
# 512-bit BLAKE2 hash.
print("BLAKE2b:", hashlib.blake2b(message).hexdigest())

Full Code:

This is the full code. You can also find it here.


import hashlib # Importing the hashlib library.

# Encoding the text into bytes and storing it in the variable 'meaasage'.
message = "Hi! This is something to encode.".encode()

# The MD5 hash.
print("MD5:", hashlib.md5(message).hexdigest())

# The SHA2 hashes.
print("SHA-256:", hashlib.sha256(message).hexdigest())
print("SHA-512:", hashlib.sha512(message).hexdigest())

# The SHA3 hashes.
print("SHA-3-256:", hashlib.sha3_256(message).hexdigest())
print("SHA-3-512:", hashlib.sha3_512(message).hexdigest())

# 256-bit Blake2 hash.
print("BLAKE2c:", hashlib.blake2s(message).hexdigest())
# 512-bit BLAKE2 hash.
print("BLAKE2b:", hashlib.blake2b(message).hexdigest())

Thank You!!