Secure Hashes and Message Digest in Python

PythonProgrammingServer Side Programming

For the secure hash and message digest process, we should use the hashlib module. This module implements a common interface for different secure hash algorithm like SHA1, SHA224, SHA256, SHA512 etc. Also the RSA’s MD5 algorithm. Older algorithms are known as the Message Digest and the new methods are called Secure Hash.

To use this module, we need to import the hashlib module in the python code.

import hashlib

In this method, there are some predefined algorithms like md5, sha1, sha224, sha256, sha512 are present. We can add additional algorithms from the OpenSSL library.

Some methods, constants of the hashlib module are as follows −

Constant hashlib.algorithm_guranteed

It will return the name of the hash algorithms, that are guaranteed to be supported by this module for all different platforms.

Constant hashlib.algorithm_available

It will return the name of the hash algorithms, which are available in the running Python interpreter.

Constant hashlib.digest_size

It will return the size of the resulting hash in bytes.

Constant hashlib.block_size

It will return the internal block size of the hash algorithm in bytes.

Method hashlib.new(name[, data])

It is a constructor. It takes a desired algorithm name as its first argument. It can use predefined hashes or other algorithms from the OpenSSL library.

Method hashlib.update(arg)

This method is used to update the hash object with given argument. Repeated call of this function is equivalent with the single call with concatenated arguments.

Method hashlib.digest()

This method is used to return the digested data which is passed through the update method. The size of the byte object is same as the digest_size. It may contain bytes in the whole range from 0 to 255.

Method hashlib.hexdigest()

This method is same as the digest method but the result will contain only hexadecimal values. This method is used to send data through the internet very easily.

Example Code

Live Demo

import hashlib
my_hash1 = hashlib.md5() #Choose md5 and update with a bytes
update_bytes = b'Python123'
my_hash1.update(update_bytes)
print("Result after digesting: " + str(my_hash1.hexdigest()))
print("Digest Size: " + str(my_hash1.digest_size))
my_hash2 = hashlib.sha256() #Choose SHA256 and update with same bytes
my_hash2.update(update_bytes)
print("Result after digesting: " + str(my_hash2.hexdigest()))
print("Digest Size: " + str(my_hash2.digest_size))

Output

Result after digesting: ae35eacb1cb6f6d38c29a04ecb2d7471
Digest Size: 16
Result after digesting: bba32ba33d6a7f3e02a96e2d7ee6860765780aee42b878007369e373ff419b1e
Digest Size: 32
raja
Published on 31-Oct-2018 12:07:37
Advertisements