Python › Module 4 › Lesson 3
Lab — File Integrity Hash Check
Hash a file with hashlib and compare digests to detect unexpected changes
Opening
Did this file change?
Hashing gives a fingerprint. If the fingerprint changes, the bytes changed—malware droppers, config edits, or honest updates. Build a tiny integrity checker.
1. hash_file.py
SHA-256 file digest — copy & runimport hashlib import sys path = sys.argv[1] if len(sys.argv) > 1 else "sample_auth.log" h = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(8192), b""): h.update(chunk) print(h.hexdigest())
import hashlib
import sys
path = sys.argv[1] if len(sys.argv) > 1 else "sample_auth.log"
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(8192), b""):
h.update(chunk)
print(h.hexdigest())Run twice and comparepython hash_file.py sample_auth.log python3 hash_file.py sample_auth.log
python hash_file.py sample_auth.log python3 hash_file.py sample_auth.log
Edit one character in the log and hash again—the digest should change completely. That avalanche effect is why hashes detect tampering.
Complete file integrity lab
Hash a file, change it, hash again, and confirm the digests differ. Record both hashes in your notes.
Knowledge Check
hashlib.sha256 is used to:
Multiple choice
Knowledge Check
True or False: Changing one byte usually changes the SHA-256 digest drastically.
True or False