DEV Community

Cover image for Build a File Integrity Checker in Python: Detect Modified, Missing, and Unchanged Files
Tahami AK SERVICES
Tahami AK SERVICES

Posted on

Build a File Integrity Checker in Python: Detect Modified, Missing, and Unchanged Files

Introduction

Have you ever wondered how you can detect whether an important file has been changed without ...Read More

A simple and powerful answer is file hashing.

In this project, we'll build a small File Integrity Checker in Python that can:

🔐 Generate SHA-256 and MD5 hashes
💾 Save a trusted baseline
🔎 Compare files against that baseline
⚠️ Detect modified files
❌ Detect missing files
✅ Identify unchanged files
📁 Monitor multiple files
💾 Keep the baseline between program runs

This is a simple project, but it introduces an important cybersecurity concept used in real ...Read More

** First: What Is File Integrity?**

A file can look normal while its contents have been changed.

For example:

config.txt

Before modification:

username=admin

After modification:

username=attacker

The filename is still the same.

But the content is different.

This is where a hash ...Read More

** What Is a Hash?**

A hash function takes data and produces a fixed-length value.

For example:

File

SHA-256

e3b0c44298fc1c149afbf4c8996fb924...

If the file changes, its hash normally ...Read More

So we can compare:

Original Hash

Current Hash

Same? → Unchanged
Different? → Modified

** Step 1 Import Python Libraries**

We'll use Python's built-in libraries:

import hashlib
import json
from pathlib import Path

No external package is required.

** Step 2 Create a Hash Function**

def calculate_hash(file_path, algorithm="sha256"):
hash_function = hashlib.new(algorithm)

with open(file_path, "rb") as file:
    while chunk := file.read(4096):
        hash_function.update(chunk)

return hash_function.hexdigest()
Enter fullscreen mode Exit fullscreen mode

Here we're reading the file in small chunks instead of loading the entire file ...Read More

That's useful when working with larger files.

** Step 3 Create a Baseline**

The baseline represents the files in their trusted state.

def create_baseline(files):
baseline = {}

for file_path in files:
    path = Path(file_path)

    if path.exists():
        baseline[str(path)] = {
            "sha256": calculate_hash(path, "sha256"),
            "md5": calculate_hash(path, "md5")
        }

return baseline
Enter fullscreen mode Exit fullscreen mode

We can then save this information as JSON.

def save_baseline(baseline, filename="baseline.json"):
with open(filename, "w") as file:
json.dump(baseline, file, indent=4)

Now our program has a record of what the trusted files ...Read More

Step 4 Compare the Current Files

Now we need to check whether anything has changed.

def check_integrity(baseline):
for file_path, hashes in baseline.items():

    path = Path(file_path)

    if not path.exists():
        print(f"[MISSING] {file_path}")
        continue

    current_hash = calculate_hash(path, "sha256")

    if current_hash == hashes["sha256"]:
        print(f"[UNCHANGED] {file_path}")
    else:
        print(f"[MODIFIED] {file_path}")
Enter fullscreen mode Exit fullscreen mode

Now we have three useful results:

[UNCHANGED]
[MODIFIED]
[MISSING]
What Happens When a File Changes?

Imagine our baseline contains:

config.txt
SHA-256:
ABC123...

Someone modifies the file.

We calculate the hash again:

config.txt
SHA-256:
XYZ789...

The values don't match.

Our program reports:

[MODIFIED] config.txt

That's the basic idea behind file ...Read More

What About Deleted Files?

Suppose the baseline contains:

config.txt
database.conf
users.csv

But someone deletes:

users.csv

The program checks whether the path exists.

It doesn't.

So we get:

[MISSING] users.csv

This makes the tool useful for detecting both ...Read More

** Complete Basic Version**

Here is a simple complete version:

import hashlib
import json
from pathlib import Path

BASELINE_FILE = "baseline.json"

def calculate_hash(file_path, algorithm="sha256"):
hash_function = hashlib.new(algorithm)

with open(file_path, "rb") as file:
    while chunk := file.read(4096):
        hash_function.update(chunk)

return hash_function.hexdigest()
Enter fullscreen mode Exit fullscreen mode

def create_baseline(files):
baseline = {}

for file_path in files:
    path = Path(file_path)

    if path.exists():
        baseline[str(path)] = {
            "sha256": calculate_hash(path, "sha256"),
            "md5": calculate_hash(path, "md5")
        }

return baseline
Enter fullscreen mode Exit fullscreen mode

def save_baseline(baseline):
with open(BASELINE_FILE, "w") as file:
json.dump(baseline, file, indent=4)

def load_baseline():
with open(BASELINE_FILE, "r") as file:
return json.load(file)

def check_integrity(baseline):
for file_path, hashes in baseline.items():

    path = Path(file_path)

    if not path.exists():
        print(f"[MISSING] {file_path}")
        continue

    current_sha256 = calculate_hash(path, "sha256")

    if current_sha256 == hashes["sha256"]:
        print(f"[UNCHANGED] {file_path}")
    else:
        print(f"[MODIFIED] {file_path}")
Enter fullscreen mode Exit fullscreen mode

files_to_monitor = [
"example.txt",
"config.txt"
]

baseline = create_baseline(files_to_monitor)

save_baseline(baseline)

print("Baseline created.\n")

baseline = load_baseline()

print("Checking file integrity...\n")

check_integrity(baseline)

Why SHA-256?

The project uses both MD5 and SHA-256 for learning and comparison.

For actual integrity/security decisions, SHA-256 is the better choice.

MD5 is considered cryptographically broken and should not be relied upon for modern ...Read More

The important concept here isn't simply memorizing algorithms.

It's understanding:

File → Hash → Baseline → Comparison → Detection

** What I Learned From This Project**

This project helped me understand that cybersecurity doesn't always require complicated tools.

A relatively small Python program can demonstrate an important security concept:

If we can establish a trusted state, we can compare future states against it and ...Read More

It also helped me practice:

Python file handling
Hashing
JSON storage
Exception/error thinking
Security monitoring
Baseline creation
Change detection
Ideas to Improve the Project

There are many ways to make this project more advanced.

For example:

Version 2

Add:

Timestamp logging
Multiple directories
Configuration files
Better error handling
Detailed modification reports

Version 3

Add:

Real-time monitoring
Email alerts
Log files
Dashboard
Scheduled scans
Windows/Linux support

Version 4

Turn it into a proper File Integrity Monitoring (FIM) tool.

That would make it much closer to a real security ...Read More

** Final Thoughts**

This project started with a simple question:

"How can I know if a file has been changed?"

The answer led to hashing, baselines, and integrity monitoring.

That's what I enjoy about cybersecurity projects.

A simple programming concept can become a practical ...Read More

Build → Test → Break → Improve → Learn.

If you're learning Python and cybersecurity, try building your own version instead of simply ...Read More

Top comments (1)

Collapse
 
tahami_akservices_cb075e profile image
Tahami AK SERVICES

This project helped me connect Python, hashing, file handling, and security monitoring in one practical exercise.