Sub topic 16
Choosing a hash for the job
This chapter assumes you know the earlier material: determinism, collisions, the birthday bound, avalanche, and the difference between a non-cryptographic hash and a cryptographic one. It also assumes you can read Python and know what a bucket index is. Here you turn that knowledge into a decision procedure.
Start with the adversary and the goal
No hash is best in general. Each job needs different properties, and they trade against each other. Two questions settle most choices.
- Is there an adversary? This means someone who gains if the hash misbehaves. Examples are an attacker who sends crafted keys, one who forges a file, or one who steals a password database.
- What must the hash guarantee? It might need to spread keys evenly, detect accidental corruption, detect deliberate tampering, prove knowledge of a secret, or make guessing expensive.
Speed is the property most often misjudged. A fast hash is good for hash tables and bad for passwords. The goal is the right cost, not the lowest cost.
The options side by side
| Job | Threat | Pick | Why |
|---|---|---|---|
| Hash table with trusted keys | None | FNV-1a, or a fast modern hash | Speed and even spread matter. Collision resistance does not. |
| Hash table with outside input | Hash flooding | Seeded hash (SipHash, keyed BLAKE2) | A secret seed stops an attacker from precomputing colliding keys. |
| Detect random corruption | Bit rot, transmission noise | CRC32 or a fast checksum | It is cheap and catches accidental damage. |
| Verify a download or build artifact | Deliberate tampering | SHA-256 | It needs second-preimage and collision resistance. |
| Authenticate a message | Forgery | HMAC-SHA-256 | Only key holders can produce a valid tag. |
| Store a password | Offline guessing | scrypt, Argon2, or bcrypt with a salt | Each guess must cost real time and memory. |
| Deduplicate files | Usually none, sometimes malicious uploads | SHA-256 | A 64-bit hash is too collision-prone at scale (birthday bound). |
Hash tables: seed it if the keys are not yours
For a table whose keys come from your own code, a fast unkeyed hash is fine. If keys come from requests, filenames, or JSON fields, an attacker can pick keys that share a bucket. Each lookup then degrades from constant time toward a linear scan, and the server stalls.
Python's built-in hash() for strings is seeded per process. That is why dict resists flooding, and also why hash("abc") differs between runs. This leads to a common mistake: never use hash() for anything that must be stable across processes or machines. Sharding, cache keys on disk, and consistent assignment of users to experiment groups all need a hash that does not change between runs.
import hashlib
def stable_shard(key: str, shards: int) -> int:
digest = hashlib.blake2b(key.encode("utf-8"), digest_size=8).digest()
return int.from_bytes(digest, "big") % shards
print(stable_shard("user-42", 8)) # same answer on every run and machine
print(stable_shard("user-43", 8))This hash is unkeyed, so it is stable but not flood-resistant. If an attacker controls the keys and you need both properties, pass a secret key= to BLAKE2 and store that key with your configuration. A key that changes on restart breaks stability, so the stability requirement and the secrecy requirement must both be met by the same stored key.
Also remember the bucket step. If you reduce with % shards and shards is not tiny relative to the hash range, the distribution is nearly even. Modulo bias is negligible for a 64-bit hash and a small bucket count, but it is real if the hash output has only a few bits.
Integrity: accident versus attack
A checksum such as CRC32 is designed for accidental errors. It is trivial to craft a different input with the same CRC32, so it says nothing about malicious changes. For tamper detection you need second-preimage and collision resistance, which means a cryptographic hash.
Two further rules apply:
- Do not use MD5 or SHA-1 for new designs. Practical collision attacks exist, so two different files can be made to share a digest. They remain acceptable for non-adversarial uses such as cache keys, but choosing SHA-256 costs almost nothing and removes the question.
- A plain hash only helps if the digest reaches you through a channel the attacker cannot alter. If the attacker can replace the file and the checksum on the same web page, the checksum proves nothing.
Authentication: add a key
SHA-256 of a message is computable by anyone, including a forger. When the receiver must know the sender held a secret, use HMAC. Do not build your own sha256(key + message). That construction is vulnerable to length extension on Merkle-Damgård hashes such as SHA-256, and HMAC exists to avoid it.
Compare tags with hmac.compare_digest. A normal == can return early at the first differing byte, which leaks timing information.
Passwords: make guessing expensive
Passwords have low entropy, so an attacker with a stolen database simply tries guesses. A fast hash such as SHA-256 lets a GPU test billions of guesses per second. A password hash fixes this in two ways. A random per-user salt defeats precomputed tables and makes identical passwords produce different records. A deliberately costly function, such as scrypt with memory hardness, slows every guess.
A complete example
This script uses each tool for its own job.
import hashlib
import hmac
import os
import tempfile
def file_sha256(path: str, chunk: int = 1 << 20) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
while block := f.read(chunk):
h.update(block)
return h.hexdigest()
def sign(key: bytes, body: bytes) -> str:
return hmac.new(key, body, hashlib.sha256).hexdigest()
def verify(key: bytes, body: bytes, tag_hex: str) -> bool:
return hmac.compare_digest(sign(key, body), tag_hex)
def hash_password(password: bytes):
salt = os.urandom(16)
return salt, hashlib.scrypt(password, salt=salt, n=2**14, r=8, p=1)
def check_password(password: bytes, salt: bytes, stored: bytes) -> bool:
candidate = hashlib.scrypt(password, salt=salt, n=2**14, r=8, p=1)
return hmac.compare_digest(candidate, stored)
with tempfile.NamedTemporaryFile(delete=False) as tmp:
tmp.write(b"release contents")
print("integrity:", file_sha256(tmp.name))
os.remove(tmp.name)
key = os.urandom(32)
body = b'{"event": "paid"}'
tag = sign(key, body)
print("webhook ok:", verify(key, body, tag))
print("tampered ok:", verify(key, b'{"event": "refund"}', tag))
salt, stored = hash_password(b"correct horse")
print("password ok:", check_password(b"correct horse", salt, stored))
print("wrong guess:", check_password(b"wrong guess", salt, stored))The file is hashed in chunks, so memory use stays constant for large files. The scrypt parameters here match the earlier example. They are a reasonable minimum, and you should raise n as hardware allows.
Common mistakes
- Using
hash()or a table hash for security. Fast and unkeyed means an attacker can forge or collide. - Using SHA-256 for passwords. It is cryptographically sound but far too fast for this job.
- Truncating digests carelessly. Cutting SHA-256 to 32 bits gives you a 32-bit hash with a birthday collision near 77,000 items.
- Rolling your own. Write FNV-1a to learn. In production, use a tested library.
Exercises
Exercise
A service assigns each user ID to one of 16 cache nodes with Python's built-in hash(user_id) % 16. After a restart, almost every user maps to a different node. Why, and what is the fix?
Show answer
Python seeds string hashing randomly per process, so hash() values change on each run. Use a stable hash instead, such as BLAKE2b or FNV-1a over the UTF-8 bytes, and reduce it with modulo. If the user IDs are attacker-controlled, use a stable keyed hash with a stored secret.
Exercise
A team stores password digests as sha256(password). They argue that SHA-256 is collision resistant, so it is safe. What is wrong with that argument, and what should they use?
Show answer
Collision resistance is not the property that matters here. Passwords are guessable, and SHA-256 is fast, so an attacker can test enormous numbers of guesses per second against a stolen database. Without a salt, identical passwords also share a digest and precomputed tables work. Use a per-user random salt with a slow, memory-hard function such as scrypt or Argon2.
Exercise
You publish a release archive and its SHA-256 digest on the same web page. Does this protect users against a compromised web server? What would improve it?
Show answer
No. An attacker who controls the server can replace both the archive and the digest. The digest only helps if it arrives through a separate trusted channel. A digital signature or a digest published elsewhere gives real protection.