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


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"



The sha1 output is like below.


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"



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


Leave a Comment