HMAC-SHA256,
**HMAC-SHA256 in Python** ===================================== HMAC-SHA256 is a cryptographic hash function that uses the SHA-256 algorithm with a secret key for message authentication. Here's an example implementation in Python: ### Using the `hmac` and `hashlib` libraries ```python import hmac import hashlib def hmac_sha256(key, message): """ Compute the HMAC-SHA256 of a message using a secret key. Args: key (bytes): The secret key. message (bytes): The message to be hashed. Returns: bytes: The HMAC-SHA256 digest. """ return hmac.new(key, message, hashlib.sha256).digest() # Example usage: key = b"my_secret_key" message = b"Hello, World!" digest = hmac_sha256(key, message) print(digest.hex()) ``` ### Using the `pycryptodome` library If you need more advanced cryptographic functionality, consider using the `pycryptodome` library, which provides a more comprehensive implementation of HMAC-SHA256: ```python from Crypto.Hash import HMAC, SHA256 def hmac_sha256(key, message): """ Compute the HMAC-SHA256 of a message using a secret key. Args: key (bytes): The secret key. message (bytes): The message to be hashed. Returns: bytes: The HMAC-SHA256 digest. """ h = HMAC.new(key, digestmod=SHA256) h.update(message) return h.digest() # Example usage: key = b"my_secret_key" message = b"Hello, World!" digest = hmac_sha256(key, message) print(digest.hex()) ``` ### Verifying a message To verify a message, you can compute the HMAC-SHA256 of the message and the expected digest, and compare the results: ```python def verify_message(key, message, expected_digest): """ Verify a message using HMAC-SHA256. Args: key (bytes): The secret key. message (bytes): The message to be verified. expected_digest (bytes): The expected HMAC-SHA256 digest. Returns: bool: True if the message is valid, False otherwise. """ computed_digest = hmac_sha256(key, message) return hmac.compare_digest(computed_digest, expected_digest) # Example usage: key = b"my_secret_key" message = b"Hello, World!" expected_digest = b"expected_digest_value" is_valid = verify_message(key, message, expected_digest) print(is_valid) ``` Note that in the `verify_message` function, we use the `hmac.compare_digest` function to compare the computed digest with the expected digest. This function is designed to prevent timing attacks.