Safe hashes and message digest in Python

For a secure hash and message digest process, we must use the hashlib module. This module implements a common interface for various secure hashing algorithms such as SHA1, SHA224, SHA256, SHA512, etc. Also RSA MD5 algorithm. The old 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 into Python code.

 import hashlib 

This method has several predefined algorithms like md5, sha1, sha224, sha256, sha512. We can add additional algorithms from the OpenSSL library.



Some methods, hashlib module constants are as follows:




The hashlib.algorithm_guranteed constant

This will return the name of the hashing algorithms that this module is guaranteed to support on all different platforms. 


The hashlib.algorithm_available constant

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






The hashlib.digest_size constant

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




The hashlib.block_size constant

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




The hashlib.new method (name [, data])

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




hashlib.update (arg) method

This method is used to update a hash object with a given argument. Calling this function again is equivalent to a single call with concatenated arguments.




hashlib.digest () method

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




hashlib.hexdigest () method

This method is the same as the digest method, but the result will contain only hexadecimal values. This method is very easy to use to send data over the Internet.




Sample Code

 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 d igesting:" + str (my_hash2.hexdigest ())) print ("Digest Size:" + str (my_hash2.digest_size)) 



Output

 Result after digesting: ae35eacb1cb6f6d38c29a04ecb2d7471 Digest Size: 16 Resulting : bba32ba33d6a7f3e02a96e2d7ee6860765780aee42b878007369e373ff419b1e Digest Size: 32 







Get Solution for free from DataCamp guru