def verify_binary_integrity(filepath, expected_checksum, checksum_function='simple_sum'):
"""
Verifies the integrity of a binary file using a specified checksum function.
Args:
filepath (str): The path to the binary file.
expected_checksum (int): The expected checksum value.
checksum_function (str): The name of the checksum function to use.
Options: 'simple_sum', 'sum_of_bytes'
Returns:
bool: True if the checksum matches, False otherwise. Returns False if file not found.
"""
try:
with open(filepath, 'rb') as f:
data = f.read()
if checksum_function == 'simple_sum':
# Simple sum of bytes (summing all byte values)
calculated_checksum = sum(data)
elif checksum_function == 'sum_of_bytes':
#Sum of all bytes in the file
calculated_checksum = sum(data)
else:
print("Invalid checksum function specified.")
return False
return calculated_checksum == expected_checksum
except FileNotFoundError:
print(f"File not found: {filepath}")
return False
except Exception as e:
print(f"An error occurred: {e}")
return False
if __name__ == '__main__':
# Example usage:
file_path = "test_file.bin" # Replace with your binary file path
# Create a dummy binary file for testing
with open(file_path, 'wb') as f:
f.write(b'\x01\x02\x03\x04\x05')
expected_checksum = 15 # Simple sum of bytes (1+2+3+4+5)
if verify_binary_integrity(file_path, expected_checksum, 'simple_sum'):
print("File integrity verified.")
else:
print("File integrity check failed.")
# Test with an incorrect checksum
expected_checksum = 20
if verify_binary_integrity(file_path, expected_checksum, 'simple_sum'):
print("File integrity verified.")
else:
print("File integrity check failed.")
# Test with a non-existent file
if verify_binary_integrity("nonexistent_file.bin", 10, 'simple_sum'):
print("File integrity verified.")
else:
print("File integrity check failed.")
Add your comment