-
Notifications
You must be signed in to change notification settings - Fork 3
Description
import hashlib
import os
import json
Function to calculate the hash of a file
def calculate_hash(file_path):
sha256_hash = hashlib.sha256()
try:
with open(file_path, "rb") as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
except FileNotFoundError:
return None
Function to create or update the hash registry
def generate_hashes(directory, output_file="hashes.json"):
hash_data = {}
for root, dirs, files in os.walk(directory):
for file in files:
path = os.path.join(root, file)
hash_data[path] = calculate_hash(path)
with open(output_file, "w") as f:
json.dump(hash_data, f, indent=4)
print(f"Hashes stored in {output_file}")
Function to check file integrity
def check_integrity(directory, hash_file="hashes.json"):
if not os.path.exists(hash_file):
print("Hash file not found. Run generate_hashes() first.")
return
with open(hash_file, "r") as f:
old_hashes = json.load(f)
for path, old_hash in old_hashes.items():
new_hash = calculate_hash(path)
if new_hash is None:
print(f"[MISSING] {path}")
elif new_hash != old_hash:
print(f"[MODIFIED] {path}")
else:
print(f"[OK] {path}")