import hashlib
def verify_text_integrity(text, expected_hash, hash_algorithm='sha256'):
"""
Verifies the integrity of a text block using a specified hash algorithm.
Args:
text (str): The text block to verify.
expected_hash (str): The expected hash value.
hash_algorithm (str): The hash algorithm to use (e.g., 'sha256', 'md5'). Defaults to 'sha256'.
Returns:
bool: True if the text's hash matches the expected hash, False otherwise.
Returns False if there's an error during hashing.
"""
try:
# Create a hash object based on the specified algorithm
hasher = hashlib.new(hash_algorithm)
# Update the hasher with the text
hasher.update(text.encode('utf-8')) # Encode to bytes
# Get the hexadecimal representation of the hash
calculated_hash = hasher.hexdigest()
# Compare the calculated hash with the expected hash
return calculated_hash == expected_hash
except Exception as e:
print(f"Error during hash calculation: {e}")
return False
if __name__ == '__main__':
# Example Usage
text_block = "This is a test text block."
expected_hash = "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8" #Example SHA256 hash
if verify_text_integrity(text_block, expected_hash):
print("Text block is valid.")
else:
print("Text block is invalid.")
#Test with an incorrect hash
if verify_text_integrity(text_block, "wrong_hash"):
print("Text block is valid.")
else:
print("Text block is invalid.")
Add your comment