Cryptographic Hashing in Python (SHA-256)
Compute secure SHA-256, SHA-512, and MD5 hashes in Python using the built-in hashlib module with streaming file support.
Python's standard library includes the hashlib module, which interfaces directly with OpenSSL to provide hardware-accelerated cryptographic hash functions. It supports SHA-224, SHA-256, SHA-384, SHA-512, SHA3, BLAKE2, and legacy algorithms like MD5 and SHA-1.
Quick Start#
Compute a SHA-256 digest of a string using hashlib.sha256():
Formats and Representations#
The hash object allows retrieving the digest in raw binary bytes or human-readable hexadecimal:
Hashing Large Files in Chunks#
When computing checksums for large files (such as ISO images, database backups, or media assets), reading the entire file into memory causes out-of-memory crashes. Read the file in 64KB chunks instead:
In Python 3.11+, hashlib also offers file_digest() for optimized streaming:
HMAC Authentication#
To generate a keyed-hash message authentication code (HMAC) for API signatures or webhook verification, use the hmac module:
Best Practices#
- Always use
hmac.compare_digest()for verification: Regular string equality==is vulnerable to timing attacks. - Encode text to bytes explicitly: Always specify
text.encode("utf-8")to avoid encoding mismatches across environments. - Select hash functions by security requirement:
- General Cryptographic Hashing: Use SHA-256 or SHA-512.
- High-Performance Cryptographic Hashing: Use
hashlib.blake2b()(RFC 7693), which is cryptographically secure and faster than MD5 or SHA-1. - Password Hashing: Never use standard cryptographic hash functions directly. Always use dedicated key derivation functions with salting and work factors, such as Argon2 (
argon2-cffi), bcrypt, orhashlib.scrypt(). - Non-Cryptographic Checksums: When security is not a requirement (e.g., hash tables or simple corruption checks), use fast checksum functions like
zlib.crc32().