1. def verify_binary_integrity(filepath, expected_checksum, checksum_function='simple_sum'):
  2. """
  3. Verifies the integrity of a binary file using a specified checksum function.
  4. Args:
  5. filepath (str): The path to the binary file.
  6. expected_checksum (int): The expected checksum value.
  7. checksum_function (str): The name of the checksum function to use.
  8. Options: 'simple_sum', 'sum_of_bytes'
  9. Returns:
  10. bool: True if the checksum matches, False otherwise. Returns False if file not found.
  11. """
  12. try:
  13. with open(filepath, 'rb') as f:
  14. data = f.read()
  15. if checksum_function == 'simple_sum':
  16. # Simple sum of bytes (summing all byte values)
  17. calculated_checksum = sum(data)
  18. elif checksum_function == 'sum_of_bytes':
  19. #Sum of all bytes in the file
  20. calculated_checksum = sum(data)
  21. else:
  22. print("Invalid checksum function specified.")
  23. return False
  24. return calculated_checksum == expected_checksum
  25. except FileNotFoundError:
  26. print(f"File not found: {filepath}")
  27. return False
  28. except Exception as e:
  29. print(f"An error occurred: {e}")
  30. return False
  31. if __name__ == '__main__':
  32. # Example usage:
  33. file_path = "test_file.bin" # Replace with your binary file path
  34. # Create a dummy binary file for testing
  35. with open(file_path, 'wb') as f:
  36. f.write(b'\x01\x02\x03\x04\x05')
  37. expected_checksum = 15 # Simple sum of bytes (1+2+3+4+5)
  38. if verify_binary_integrity(file_path, expected_checksum, 'simple_sum'):
  39. print("File integrity verified.")
  40. else:
  41. print("File integrity check failed.")
  42. # Test with an incorrect checksum
  43. expected_checksum = 20
  44. if verify_binary_integrity(file_path, expected_checksum, 'simple_sum'):
  45. print("File integrity verified.")
  46. else:
  47. print("File integrity check failed.")
  48. # Test with a non-existent file
  49. if verify_binary_integrity("nonexistent_file.bin", 10, 'simple_sum'):
  50. print("File integrity verified.")
  51. else:
  52. print("File integrity check failed.")

Add your comment