Build a Python File Hash Checker to Catch Tampered Downloads
You download an ISO, a tool, a firmware update. How do you know nobody tampered with it on the way? Software vendors publish checksums — cryptographic hashes of the original file. If your download’s hash doesn’t match, something changed. Today we build a Python script that verifies file integrity automatically.
How Hashing Works
A hash function (like SHA-256) turns any file into a fixed-length fingerprint. Change even one byte of the file, and the fingerprint changes completely. That’s what makes hashes perfect tamper detectors: you can’t modify the file without breaking the match.
The Code
import hashlibimport sysdef hash_file(path, algorithm="sha256"): """Hash a file in chunks (memory-safe for huge files).""" h = hashlib.new(algorithm) with open(path, "rb") as f: for chunk in iter(lambda: f.read(65536), b""): h.update(chunk) return h.hexdigest()def verify(path, expected, algorithm="sha256"): actual = hash_file(path, algorithm) print(f"Algorithm : {algorithm}") print(f"Expected : {expected}") print(f"Actual : {actual}") if actual.lower() == expected.lower(): print("\nMATCH — file is intact.") return True else: print("\nMISMATCH — file may be tampered with. DO NOT USE.") return Falseif __name__ == "__main__": if len(sys.argv) != 3: print("Usage: python3 hashcheck.py <file> <expected_hash>") sys.exit(1) ok = verify(sys.argv[1], sys.argv[2]) sys.exit(0 if ok else 1)
How It Works
- Chunked reading — the file is read in 64KB pieces, so even a 4GB ISO won’t eat your RAM.
- hashlib — Python’s built-in crypto library; no installs needed. Swap “sha256” for “sha512” or “md5” if a vendor publishes a different checksum.
- Case-insensitive compare — hashes are hex; vendors sometimes publish uppercase.
Try It
# 1. Hash a file you downloadedpython3 hashcheck.py ubuntu.iso# 2. Compare with the checksum on the vendor's official sitepython3 hashcheck.py ubuntu.iso 45f873de9f8cb637345d6fec344634814...
If it prints MATCH, your file is byte-for-byte identical to what the vendor published. MISMATCH means re-download from the official source — never run a mismatched installer.
Why This Matters
Supply-chain attacks — where attackers poison legitimate downloads — are rising. Verifying checksums is the simplest defense, and most people skip it because it feels tedious. Your script removes the tedium: one command, instant verdict.
Level Up
- Auto-fetch the expected hash from the vendor’s checksum file and compare in one step.
- Hash an entire directory and store a baseline, then re-check weekly to detect unauthorized changes (that’s how real file-integrity monitors like AIDE work).
- Add argparse for a cleaner CLI with algorithm selection.
You just built a defensive security tool used in every SOC on earth. Small script, real protection.



Comments
Post a Comment