How to use Hashlib to encrypt a string in python

Using hashlib in python :

Hashlib module contains different types of secure hash algorithm methods. You can use these methods directly to create hash of different values. In this tutorial we will learn how to use hashlib module with a simple example.

Algorithms included in hashlib :

Hashlib module includes FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512 as well as RSA’s MD5 algorithm.

How to use hashlib :

For each methods, one constructor is available. For example, sha512() is used to create a SHA-512 object. Following hash algorithms are always present in all python installed systems : sha1(), sha224(), sha256(), sha384(), sha512(), blake2b(), and blake2s(). md5() is also available in most of the python versions. We can also check what algorithms are availabe and what algorithms are supported by this module on all systems :

Check for available algorithms in hashlib :

Two constants are available in hashlib to print out the list of all available and supported algorithms : hashlib.algorithms_guaranteed : It contains a set of name of all the algorithms that guaranteed to be supported on all platforms by this module. hashlib.algorithms_available : It also contains a set of names of all the algorithms that are available in the running python interpreter. ‘algorithms_guaranteed’ is a subset of ‘algorithms_available’. You can use the above two constants to print out all algorithms :

import hashlib

print ("Algorithms Guaranteed :")
print hashlib.algorithms_guaranteed
print ("Algorithms Available :")
print hashlib.algorithms_available

On my machine , it gives output like below :

Algorithms Guaranteed :
set(['sha1', 'sha224', 'sha384', 'sha256', 'sha512', 'md5'])
Algorithms Available :
set(['SHA1', 'MDC2', 'SHA', 'SHA384', 'ecdsa-with-SHA1', 'SHA256', 'SHA512', 'md4', 'md5', 'sha1', 'dsaWithSHA', 'DSA-SHA', 'sha', 'sha224', 'dsaEncryption', 'DSA', 'ripemd160', 'mdc2', 'MD5', 'MD4', 'sha384', 'SHA224', 'sha256', 'sha512', 'RIPEMD160'])

Example of hashlib :

First, we will create a object of the type of algorithm. Then we will pass the input to the ‘update(arg)’ method of the hash object. This method takes only byte inputs. So, if you want to get the hash value for a string, pass it as b’string’ . And finally, call the ‘digest()’ method to get the secure hash value. Following example will show you how to get ‘sha256’ and ‘md5’ hash using hashlib:

import hashlib

#sha25 

sha_obj = hashlib.sha256()
sha_obj.update(b'Hello World!')

print ("sha256 hash : ",sha_obj.digest())

#md5
md5_obj = hashlib.md5(b'Hello World!')
md5_obj.update(b'Hello World!')

print ("md5 hash : ",md5_obj.digest())

It will give the following output :

sha256 hash :  b'\x7f\x83\xb1e\x7f\xf1\xfcS\xb9-\xc1\x81H\xa1\xd6]\xfc-K\x1f\xa3\xd6w(J\xdd\xd2\x00\x12m\x90i'
md5 hash :  b'\xeeA\xc9hS\x0fw\x15\xabp\x80[4\x1c9V'

Similar tutorials :