Python hashlib Module Tutorial

Python hashlib module provides methods for hash and security-related functions. The hashlib provides FIPS secure hash algorithms like SHA1, SHA224, SHA256, SHA384, SHA512, and RSA MD5. These hash algorithms also called "secure hash" or "message digest". The hashlib is based on the OpenSSL library which is a very popular library that provides cryptographic libraries and functions.

List Available Hash Algorithms

Some algortihms are available for all platforms and operating systems but some of them are not. The availabl hash algorithms for the current platform can be listed with the algorithms_available variable.

import hashlib

print(hashlib.algorithms_available)

The output is like below.

{'blake2b', 'sha512_224', 'sha1', 'shake_128', 'md5', 'shake_256', 'sha384', 'sm3', 'sha224', 'sha3_224', 'sha3_384', 'ripemd160', 'md5-sha1', 'whirlpool', 'sha256', 'sha3_256', 'blake2s', 'sha512_256', 'md4', 'sha3_512', 'sha512'}

Calculate sha1

Sha1 is the first hash algorithm for the sha family. The sha1 can be calculated with the update() method of the sha1 object. The data we want to calculate sha1 can be provided as a parameter.

import hashlib

sha1 = hashlib.sha1()

data = "this is a text"

sha1.update(data.encode("utf-8"))

print(sha1.hexdigest())

The sha1 output is like below.

703c445982e074e33a05c161d221217f2facbf5e

Calculate sha256

The sha1 is not secure as today and sha256 should be used for a secure alternative. In the following example, we will calculate the sha256 of the provided data.

import hashlib

sha256 = hashlib.sha256()

data = "this is a text"

sha256.update(data.encode("utf-8"))

print(sha256.hexdigest())

The output is like below. We can see that it is 256 bit which is equal to the 32 bytes.

01c917c4fae3bfd2937f008cf7a2f0ab3f55bf5ac404dc3f68429b72e565c4ef

Leave a Comment