- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Secure Hashes and Message Digest in Python
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.
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 −
It will return the name of the hash algorithms, that are guaranteed to be supported by this module for all different platforms.
It will return the name of the hash algorithms, which are available in the running Python interpreter.
It will return the size of the resulting hash in bytes.
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.
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.
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.
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.
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))
Result after digesting: ae35eacb1cb6f6d38c29a04ecb2d7471 Digest Size: 16 Result after digesting: bba32ba33d6a7f3e02a96e2d7ee6860765780aee42b878007369e373ff419b1e Digest Size: 32
Kickstart Your Career
Get certified by completing the courseGet Started