Python Hashlib With Examples

In this tutorial, we are going to learn about Python Hashlib module. We can use python hashlib module to generate message digest or secure hash from the source message. In our previous tutorial we learnt about Python Math.

Python Hashlib

For generating python secure hash message, we need to use hashlib module.

Python hashlib hashing function takes variable length of bytes and converts it into a fixed length sequence. This is a one way function. That means, you hash a message, you get a fixed length sequence. But you cannot get the original message from those fixed length sequence.

In cryptography, a hash algorithm is considered to be better if the original message cannot be decrypted from the hash message. Also changing one byte in the original message makes significant change in the message digest value.

Python secure hash values are used in storing password in encrypted form. So even the application owner won’t have access to user password, passwords are matched when user enters the password again and hash value is calculated and compared with the stored value.

Available Hashing Algorithms

We can use algorithms_available function to get the list of all the algorithms available in the system, including those available through OpenSSl. Duplicate algorithm names can be seen also.

Again, by using algorithms_guaranteed function you can see the algorithms present in the module. See the following code.

For my system, the output was like this below. It can differ based on the operating system configurations.

Python hashlib example

To use Python hashlib module, you just have to know few functions. By using hashlib.encryption_algorithm_name(b"message") function, you can hash the whole message at once.

Also, you can use the update() function to append byte message to the secure hash value. In both case, the output will be same. Finally, by using digest() function you can get the secure hash.

Note that, b is written in the left of the message to be hashed. This b indicates that that string is a byte string. Let’s look at the hashlib example for more clarity.

So the output will be

python-hashlib

So, this is all about Python hashlib module. Hope that you learned well. See the official reference to learn more about it.

By admin

Leave a Reply