import hashlib
import os
import json
def calculate_file_hash(file_path):
"""Calculate the SHA-256 hash of a file."""
if not os.path.isfile(file_path):
raise FileNotFoundError(f"The file '{file_path}' does not exist.")
sha256_hash = hashlib.sha256()
with open(file_path, "rb") as f:
# Read and update hash string value in blocks of 4K
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
def save_hash(file_path, hash_value):
"""Save the hash value to a .json file."""
if not os.path.exists("file_hashes.json"):
with open("file_hashes.json", "w") as f:
json.dump({}, f)
with open("file_hashes.json", "r+") as f:
try:
data = json.load(f)
except json.JSONDecodeError:
data = {}
data[file_path] = hash_value
f.seek(0)
json.dump(data, f, indent=4)
def check_file_integrity(file_path):
"""Check if a file's hash matches the stored hash."""
current_hash = calculate_file_hash(file_path)
if os.path.exists("file_hashes.json"):
with open("file_hashes.json", "r") as f:
data = json.load(f)
stored_hash = data.get(file_path)
if stored_hash:
if current_hash == stored_hash:
return "File is intact."
else:
return "File has been modified!"
else:
return "No stored hash found for this file."
else:
return "No hash records found. Please save the hash first."
if __name__ == "__main__":
action = input("Enter 'save' to save a file hash or 'check' to check file integrity: ").strip().lower()
file_path = input("Enter the path of the file: ")
if action == 'save':
file_hash = calculate_file_hash(file_path)
save_hash(file_path, file_hash)
print(f"Hash for '{file_path}' saved.")
elif action == 'check':
result = check_file_integrity(file_path)
print(result)
else:
print("Invalid action. Please enter 'save' or 'check'.")