import json
import hashlib
import logging
def verify_form_integrity(form_data, config_file="integrity_config.json"):
"""
Verifies the integrity of form data against a configuration file.
Args:
form_data (dict): A dictionary containing the form data.
config_file (str): Path to the configuration file.
Returns:
bool: True if the form data is valid, False otherwise.
"""
try:
with open(config_file, "r") as f:
config = json.load(f)
except FileNotFoundError:
logging.error(f"Configuration file not found: {config_file}")
return False
except json.JSONDecodeError:
logging.error(f"Invalid JSON format in configuration file: {config_file}")
return False
expected_hash = config.get("expected_hash")
if not expected_hash:
logging.warning("No expected hash found in configuration.")
return True # Consider valid if no hash is defined
# Generate a hash of the form data (e.g., SHA-256)
data_string = json.dumps(form_data, sort_keys=True).encode('utf-8') # Consistent string representation
calculated_hash = hashlib.sha256(data_string).hexdigest()
# Compare the calculated hash with the expected hash
if calculated_hash == expected_hash:
return True
else:
logging.warning(f"Form data integrity check failed. Expected: {expected_hash}, Calculated: {calculated_hash}")
return False
if __name__ == '__main__':
# Example usage
form_data = {"name": "John Doe", "email": "john.doe@example.com", "age": 30}
# Create a sample configuration file (integrity_config.json)
config = {"expected_hash": "e5b7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7"}
with open("integrity_config.json", "w") as f:
json.dump(config, f)
is_valid = verify_form_integrity(form_data)
print(f"Form data is valid: {is_valid}")
# Test with incorrect data
incorrect_form_data = {"name": "Jane Doe", "email": "jane.doe@example.com", "age": 25}
is_valid = verify_form_integrity(incorrect_form_data)
print(f"Form data is valid: {is_valid}")
Add your comment