Developer Documentation
Python
Updated September 18, 2026

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():

Python
1import hashlib23# 1. Strings must be encoded into bytes before hashing4data = "ToolPorta Secure Payload".encode("utf-8")56# 2. Compute digest7digest = hashlib.sha256(data).hexdigest()89print(digest)10# Output: "ebaaafbb17fa16f0be7ab74c04e07c985bf0913468f82bb8d95627ee83a1a7f2"

Formats and Representations#

The hash object allows retrieving the digest in raw binary bytes or human-readable hexadecimal:

Python
1import hashlib23h = hashlib.sha256(b"Hello World")45# 64-character lowercase hex string6hex_str = h.hexdigest()7print("Hex:", hex_str)89# 32-byte raw binary representation10raw_bytes = h.digest()11print("Bytes length:", len(raw_bytes))  # 32

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:

Python
1import hashlib2from pathlib import Path34def hash_file(file_path: str | Path, algorithm: str = "sha256") -> str:5    hasher = hashlib.new(algorithm)6    chunk_size =   # 64 KB chunks78    with open(file_path, "rb") as f:9        while chunk := f.read(chunk_size):10            hasher.update(chunk)1112    return hasher.hexdigest()1314# Example usage15# file_checksum = hash_file("dataset.csv")

In Python 3.11+, hashlib also offers file_digest() for optimized streaming:

Python
1import hashlib23# Available in Python 3.11+4with open("dataset.csv", "rb") as f:5    digest = hashlib.file_digest(f, "sha256").hexdigest()

HMAC Authentication#

To generate a keyed-hash message authentication code (HMAC) for API signatures or webhook verification, use the hmac module:

Python
1import hmac2import hashlib34secret_key = b"super-secret-api-key"5payload = b'{"event":"payment_success","amount":100}'67# Generate HMAC-SHA256 signature8signature = hmac.new(secret_key, payload, hashlib.sha256).hexdigest()9print("HMAC Signature:", signature)1011# Timing-attack safe comparison against separately received expected signature12expected_signature = signature  # In real applications, this comes from an incoming request header13is_valid = hmac.compare_digest(signature, expected_signature)14print("Valid:", is_valid)

Best Practices#

  1. Always use hmac.compare_digest() for verification: Regular string equality == is vulnerable to timing attacks.
  2. Encode text to bytes explicitly: Always specify text.encode("utf-8") to avoid encoding mismatches across environments.
  3. 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, or hashlib.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().

References#

Implement Hashing in other languages: