1. import hashlib
  2. import time
  3. def hash_data_with_retry(data, algorithm='sha256', retry_interval=5, max_retries=3):
  4. """Hashes user data with retry mechanism."""
  5. for attempt in range(max_retries):
  6. try:
  7. # Hash the data using the specified algorithm
  8. hash_object = hashlib.new(algorithm)
  9. hash_object.update(str(data).encode('utf-8')) # Convert data to string and encode
  10. hex_dig = hash_object.hexdigest()
  11. return hex_dig # Return the hash if successful
  12. except Exception as e:
  13. print(f"Hash error on attempt {attempt + 1}: {e}")
  14. if attempt < max_retries - 1:
  15. time.sleep(retry_interval) # Wait before retrying
  16. else:
  17. print("Max retries reached. Returning None.")
  18. return None # Return None if all retries fail
  19. if __name__ == '__main__':
  20. # Example usage
  21. user_data = "some user data"
  22. hashed_value = hash_data_with_retry(user_data)
  23. if hashed_value:
  24. print(f"Hashed value: {hashed_value}")
  25. else:
  26. print("Hashing failed after multiple retries.")

Add your comment