hashlib
Library in PythonThe hashlib
library in Python provides various hashing algorithms. Let's explore how to use them.
First, we need to encode our message into bytes using UTF-8 encoding:
import hashlib
# encode it to bytes using UTF-8 encoding
message = "Some text to hash".encode()
MD5 is an older and less secure hashing algorithm. It's not recommended for use due to its vulnerability to collisions:
# hash with MD5 (not recommended)
print("MD5:", hashlib.md5(message).hexdigest())
SHA-2 includes SHA-256 and SHA-512, which are more secure and commonly used:
# hash with SHA-2 (SHA-256 & SHA-512)
print("SHA-256:", hashlib.sha256(message).hexdigest())
print("SHA-512:", hashlib.sha512(message).hexdigest())
SHA-2 is a family of four hash functions: SHA-224, SHA-256, SHA-384, and SHA-512. SHA-256 and SHA-512 are the most commonly used.
SHA-3 is the latest family of hashing algorithms and offers better security:
# hash with SHA-3
print("SHA-3-256:", hashlib.sha3_256(message).hexdigest())
print("SHA-3-512:", hashlib.sha3_512(message).hexdigest())
BLAKE2 is faster than SHA-1, SHA-2, SHA-3, and even MD5, and more secure than SHA-2:
# hash with BLAKE2
# 256-bit BLAKE2 (or BLAKE2s)
print("BLAKE2c:", hashlib.blake2s(message).hexdigest())
# 512-bit BLAKE2 (or BLAKE2b)
print("BLAKE2b:", hashlib.blake2b(message).hexdigest())
BLAKE2 hashes are faster than SHA-1, SHA-2, SHA-3, and MD5, and more secure than SHA-2. BLAKE2 is widely used and has been integrated into major cryptography libraries such as OpenSSL and Sodium.
To hash an entire file, you can read the file content and pass the bytes to any of the functions we covered.
For further reading, refer to the official Python documentation for the hashlib
module.
Finally, if you're interested in ethical hacking, check out our guide where we build 35+ hacking tools and scripts using Python!
How to Use Hashing Algorithms in Python using hashlib - https://thepythoncode.com/article/build-a-password-manager-in-python