-
Notifications
You must be signed in to change notification settings - Fork 3
Description
import hashlib
import os
import json
HASH_FILE = "file_hashes.json"
def calculate_hash(file_path, algorithm="sha256"):
"""Calculate the hash of a file."""
h = hashlib.new(algorithm)
try:
with open(file_path, "rb") as f:
while chunk := f.read(8192):
h.update(chunk)
return h.hexdigest()
except FileNotFoundError:
print(f"[ERROR] File not found: {file_path}")
return None
def save_hashes(file_paths, algorithm="sha256"):
"""Calculate and save hash values of given files."""
hashes = {}
for path in file_paths:
hash_val = calculate_hash(path, algorithm)
if hash_val:
hashes[path] = hash_val
with open(HASH_FILE, "w") as f:
json.dump(hashes, f, indent=4)
print(f"[INFO] Hashes saved to {HASH_FILE}")
def verify_integrity(algorithm="sha256"):
"""Verify file integrity by comparing current and stored hashes."""
if not os.path.exists(HASH_FILE):
print(f"[ERROR] Hash file not found. Please run in save mode first.")
return
with open(HASH_FILE, "r") as f:
stored_hashes = json.load(f)
for path, old_hash in stored_hashes.items():
new_hash = calculate_hash(path, algorithm)
if not new_hash:
continue
if new_hash == old_hash:
print(f"[OK] File is unchanged: {path}")
else:
print(f"[WARNING] File has been modified: {path}")
if name == "main":
import argparse
parser = argparse.ArgumentParser(description="File Integrity Checker")
parser.add_argument("mode", choices=["save", "verify"], help="Mode: 'save' or 'verify'")
parser.add_argument("files", nargs="*", help="File paths to monitor (required in save mode)")
args = parser.parse_args()
if args.mode == "save":
if not args.files:
print("[ERROR] No files provided to save.")
else:
save_hashes(args.files)
elif args.mode == "verify":
verify_integrity()