1. import json
  2. import hashlib
  3. import logging
  4. def verify_form_integrity(form_data, config_file="integrity_config.json"):
  5. """
  6. Verifies the integrity of form data against a configuration file.
  7. Args:
  8. form_data (dict): A dictionary containing the form data.
  9. config_file (str): Path to the configuration file.
  10. Returns:
  11. bool: True if the form data is valid, False otherwise.
  12. """
  13. try:
  14. with open(config_file, "r") as f:
  15. config = json.load(f)
  16. except FileNotFoundError:
  17. logging.error(f"Configuration file not found: {config_file}")
  18. return False
  19. except json.JSONDecodeError:
  20. logging.error(f"Invalid JSON format in configuration file: {config_file}")
  21. return False
  22. expected_hash = config.get("expected_hash")
  23. if not expected_hash:
  24. logging.warning("No expected hash found in configuration.")
  25. return True # Consider valid if no hash is defined
  26. # Generate a hash of the form data (e.g., SHA-256)
  27. data_string = json.dumps(form_data, sort_keys=True).encode('utf-8') # Consistent string representation
  28. calculated_hash = hashlib.sha256(data_string).hexdigest()
  29. # Compare the calculated hash with the expected hash
  30. if calculated_hash == expected_hash:
  31. return True
  32. else:
  33. logging.warning(f"Form data integrity check failed. Expected: {expected_hash}, Calculated: {calculated_hash}")
  34. return False
  35. if __name__ == '__main__':
  36. # Example usage
  37. form_data = {"name": "John Doe", "email": "john.doe@example.com", "age": 30}
  38. # Create a sample configuration file (integrity_config.json)
  39. config = {"expected_hash": "e5b7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7e7"}
  40. with open("integrity_config.json", "w") as f:
  41. json.dump(config, f)
  42. is_valid = verify_form_integrity(form_data)
  43. print(f"Form data is valid: {is_valid}")
  44. # Test with incorrect data
  45. incorrect_form_data = {"name": "Jane Doe", "email": "jane.doe@example.com", "age": 25}
  46. is_valid = verify_form_integrity(incorrect_form_data)
  47. print(f"Form data is valid: {is_valid}")

Add your comment