Cryptographic Hash Functions
SHA-256, SHA-3, and hash properties
Skills taught: crypto.hashing
Hash Function Properties
A cryptographic hash function takes any input and produces a fixed-size output (digest). Every good hash function satisfies five properties: deterministic, fast, preimage resistant (one-way), second-preimage resistant, and collision resistant.
- Deterministic — same input always produces same output
- Avalanche effect — tiny input change flips ~50% of output bits
- Preimage resistant — given hash(x), cannot find x
- Second-preimage resistant — given x, cannot find y≠x with hash(y)=hash(x)
- Collision resistant — cannot find any two inputs with the same hash
- Collision Resistance
- It must be computationally infeasible to find two different inputs that produce the same hash. MD5 and SHA-1 have practical collisions; SHA-256 does not.
Using Hash Functions in Python
import hashlib
import hmac
# --- SHA-256: standard choice ---
data = b"Important document content"
hash_sha256 = hashlib.sha256(data).hexdigest()
print("SHA-256:", hash_sha256) # 32 bytes = 64 hex chars
# --- SHA-3: modern alternative ---
hash_sha3 = hashlib.sha3_256(data).hexdigest()
print("SHA3-256:", hash_sha3)
# --- BLAKE2b: fastest option, good for checksums ---
hash_blake = hashlib.blake2b(data, digest_size=32).hexdigest()
print("BLAKE2b:", hash_blake)
# --- HMAC: keyed hash for message authentication ---
key = b"my_secret_key"
mac = hmac.new(key=key, msg=data, digestmod="sha256")
print("HMAC-SHA256:", mac.hexdigest())
# --- File integrity check ---
def sha256_file(path: str) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
return h.hexdigest()
# --- WRONG: MD5 and SHA-1 are broken ---
# hashlib.md5(data) # broken for security, avoid
# hashlib.sha1(data) # collision attacks proven, avoid
Warning: MD5 and SHA-1 have practical collision attacks. Never use them for security. Use SHA-256, SHA-3-256, or BLAKE2 at minimum. Never use SHA-256 to store passwords — use Argon2id or bcrypt.
SHA-256 vs SHA-3-256
- SHA-256: SHA-2 family, Merkle-Damgård construction, NIST standard
- SHA-3-256: Keccak sponge construction, completely different design from SHA-2
HMAC — Keyed Hashing
A plain hash authenticates data but not who sent it. HMAC (Hash-based Message Authentication Code) combines a hash with a secret key to prove both integrity and origin.
import hmac, hashlib, os
key = os.urandom(32) # shared secret between sender and receiver
message = b"Transfer $1000 to account 9876"
# Sender computes MAC
my_mac = hmac.new(key=key, msg=message, digestmod="sha256").hexdigest()
# Receiver verifies (constant-time comparison)
received_mac = my_mac # from the message packet
if hmac.compare_digest(my_mac, received_mac):
print("Message is authentic")
else:
print("Message was tampered!")
Tip: Use HMAC-SHA256 for API request signing, webhook verification, and cookie integrity checks. It prevents length-extension attacks that bare SHA-256 is vulnerable to.
Frequently Asked Questions
Can I use SHA-256 to store passwords?
No. SHA-256 is too fast — an attacker can try billions of guesses per second on a GPU. Use bcrypt, Argon2id, or scrypt, which are intentionally slow and memory-intensive.
What is a length-extension attack?
With SHA-256 (Merkle-Damgård construction), given hash(msg), an attacker can compute hash(msg || extra_data) without knowing the original msg. HMAC prevents this by double-wrapping the key.
What is the best hash algorithm to use today?
SHA-256 for general use; SHA-3-256 for new protocols where design diversity matters; BLAKE2 for high-performance hashing. SHA-1 and MD5 must not be used for security.