Hashing & Integrity
A hash function maps any amount of data to a short, fixed-size digest. Cryptographic hashes such as SHA-256 are designed so that nobody can find two inputs with the same digest or work backwards from a digest to the input. That makes a digest a trustworthy fingerprint: if the fingerprint matches, the data is the same.
Hashing in Python
Python's hashlib module provides the standard algorithms. You feed it bytes (encode text first) and read the digest as raw bytes or as a hex string:
import hashlib
data = "Hello, security!".encode("utf-8")
sha = hashlib.sha256(data)
print(sha.hexdigest())
print(len(sha.digest()), "bytes =", len(sha.digest()) * 8, "bits")
for name in ["md5", "sha1", "sha256", "sha512", "sha3_256", "blake2b"]:
digest = hashlib.new(name, data).hexdigest()
print(f"{name:<9} {len(digest) * 4:>3} bits {digest[:16]}…")f886abf1e4d5cef302b46d172f4a90a23ca9d6141bb2f569fe561ca3cd754316
32 bytes = 256 bits
md5 128 bits 03f58140aeb71935…
sha1 160 bits 65ff9b7626863f4a…
sha256 256 bits f886abf1e4d5cef3…
sha512 512 bits 8c131d34b8244beb…
sha3_256 256 bits 432edccfc35e0df9…
blake2b 512 bits af954e04af04bf50…
Which algorithms are safe?
| Algorithm | Digest size | Status |
|---|---|---|
| MD5 | 128 bits | Broken: collisions can be produced on a laptop. Only for non-security checksums |
| SHA-1 | 160 bits | Broken for collisions since 2017. Avoid |
| SHA-256 / SHA-512 (SHA-2) | 256 / 512 bits | Safe and the most widely used |
| SHA-3 | 224–512 bits | Safe; a completely different design, useful as a backup |
| BLAKE2 / BLAKE3 | up to 512 bits | Safe and very fast |
A collision is two different inputs with the same digest. For MD5 and SHA-1 an attacker can create pairs of documents that hash the same, for example a harmless and a malicious certificate. Use SHA-256 or better for anything security-related.
Integrity checks
The most common use of hashes is checking that data hasn't changed. Software projects publish the SHA-256 of each download; you hash the file you received and compare. Hashing large files is done in chunks so the whole file never needs to be in memory:
import hashlib
import io
def sha256_stream(stream, chunk_size=4096):
h = hashlib.sha256()
while chunk := stream.read(chunk_size):
h.update(chunk)
return h.hexdigest()
release = b"#!/bin/sh\necho 'installing tool v2.1'\n" * 500
published = hashlib.sha256(release).hexdigest() # what the website lists
downloaded_ok = io.BytesIO(release)
downloaded_bad = io.BytesIO(release.replace(b"v2.1", b"v2.2", 1))
for label, stream in [("original", downloaded_ok), ("modified", downloaded_bad)]:
actual = sha256_stream(stream)
print(f"{label}: {'MATCH' if actual == published else 'MISMATCH'} {actual[:20]}…")original: MATCH e152f43a88ad65be6bde…
modified: MISMATCH 23c4f2069b20bf584008…
Changing a single character out of 19,000 bytes gives a completely different digest. That is the avalanche effect.
Warning: A hash only proves integrity if the expected digest comes from a trusted place. If an attacker can replace both the download and the digest on the same website, the check proves nothing. That is what digital signatures solve (a later lesson).
Detecting changed files
Integrity monitoring tools (often called FIM, file integrity monitoring) keep a baseline of hashes for important files and alert when one changes unexpectedly, for example a modified system binary or web page:
import hashlib
def fingerprint(files):
return {path: hashlib.sha256(content).hexdigest() for path, content in files.items()}
before = {
"/etc/passwd": b"root:x:0:0:root:/root:/bin/bash\n",
"/var/www/index.html": b"<h1>Welcome</h1>",
"/usr/bin/login": b"\x7fELF...original",
}
baseline = fingerprint(before)
after = dict(before)
after["/usr/bin/login"] = b"\x7fELF...replaced"
after["/var/www/shell.php"] = b"<?php ... ?>"
del after["/var/www/index.html"]
current = fingerprint(after)
for path in sorted(baseline.keys() | current.keys()):
if path not in current:
print("DELETED ", path)
elif path not in baseline:
print("NEW ", path)
elif baseline[path] != current[path]:
print("CHANGED ", path)CHANGED /usr/bin/login
DELETED /var/www/index.html
NEW /var/www/shell.php
A replaced login binary or an unexpected .php file in the web root are classic signs of compromise. The baseline itself must be stored where an attacker can't rewrite it.
Hashes are not secret
Anyone can compute a hash, so a hash of a guessable value hides nothing. If you "anonymise" email addresses or phone numbers by hashing them, anyone with a list of candidates can hash each one and match. To bind a hash to a secret key, use an HMAC (next lesson); to store passwords, use a slow, salted function (the lesson after).
import hashlib
pin_hash = hashlib.sha256(b"4821").hexdigest()
print("stored:", pin_hash[:24] + "…")
# There are only 10,000 four-digit PINs: hashing hides very little.
print("possible PINs:", 10 ** 4)
print("possible 256-bit digests: 2 **", 256)
print("digest length doesn't matter when the INPUT space is tiny")stored: a388f562e286fdf28986f925…
possible PINs: 10000
possible 256-bit digests: 2 ** 256
digest length doesn't matter when the INPUT space is tiny
Go further: Hash Function Properties and the Birthday Bound explains why a 256-bit hash gives 128-bit collision resistance, with both searches run on toy hashes.
Test yourself
Which of these hash functions is still considered safe for security use?
- MD5
- SHA-1
- SHA-256
- CRC32
You download a file and its SHA-256 matches the value on the same (compromised) website. What has been proven?
- The file is authentic
- Only that the file matches what that website lists
- The file is virus-free
- The file is encrypted
Why is hashing phone numbers a weak way to anonymise them?
- SHA-256 is too slow
- The set of possible phone numbers is small enough to hash them all and compare
- Hashes can be decrypted
- Phone numbers contain symbols