1. import hashlib
  2. def verify_text_integrity(text, expected_hash, hash_algorithm='sha256'):
  3. """
  4. Verifies the integrity of a text block using a specified hash algorithm.
  5. Args:
  6. text (str): The text block to verify.
  7. expected_hash (str): The expected hash value.
  8. hash_algorithm (str): The hash algorithm to use (e.g., 'sha256', 'md5'). Defaults to 'sha256'.
  9. Returns:
  10. bool: True if the text's hash matches the expected hash, False otherwise.
  11. Returns False if there's an error during hashing.
  12. """
  13. try:
  14. # Create a hash object based on the specified algorithm
  15. hasher = hashlib.new(hash_algorithm)
  16. # Update the hasher with the text
  17. hasher.update(text.encode('utf-8')) # Encode to bytes
  18. # Get the hexadecimal representation of the hash
  19. calculated_hash = hasher.hexdigest()
  20. # Compare the calculated hash with the expected hash
  21. return calculated_hash == expected_hash
  22. except Exception as e:
  23. print(f"Error during hash calculation: {e}")
  24. return False
  25. if __name__ == '__main__':
  26. # Example Usage
  27. text_block = "This is a test text block."
  28. expected_hash = "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8" #Example SHA256 hash
  29. if verify_text_integrity(text_block, expected_hash):
  30. print("Text block is valid.")
  31. else:
  32. print("Text block is invalid.")
  33. #Test with an incorrect hash
  34. if verify_text_integrity(text_block, "wrong_hash"):
  35. print("Text block is valid.")
  36. else:
  37. print("Text block is invalid.")

Add your comment