Keyed-Hashing for Message Authentication in python

Keyed-Hashing for Message Authentication (HMAC) provides secure message authentication using cryptographic hash functions combined with a secret key. Python's hmac module implements this mechanism to ensure data integrity and authenticity during transmission or storage.

The basic concept involves generating a cryptographic hash from the actual data combined with a shared secret key. The recipient can verify the message authenticity by recalculating the hash using the same secret key.

Syntax

hmac.new(key, msg=None, digestmod=None)

Parameters:

  • key ? The shared secret key (bytes object)

  • msg ? The message to hash (optional, can be added later)

  • digestmod ? Hash algorithm to use (e.g., hashlib.md5, hashlib.sha1, hashlib.sha256)

Key Methods

  • hmac.update(message) ? Appends message data to the HMAC object

  • hmac.digest() ? Returns the binary digest of the data

  • hmac.hexdigest() ? Returns the digest as a hexadecimal string

  • hmac.copy() ? Creates a copy of the HMAC object

Example with MD5

Here's how to create an HMAC using the MD5 hash algorithm ?

import hashlib
import hmac

# Message data
message_data = b'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse tristique condimentum viverra.'

# Secret key  
secret_key = b'402xy5#'

# Generate HMAC using MD5
my_hmac = hmac.new(secret_key, message_data, hashlib.md5)

print("MD5 Digest:", my_hmac.hexdigest())
print("Algorithm Name:", my_hmac.name)
print("Block Size:", my_hmac.block_size, "bytes")
print("Digest Size:", my_hmac.digest_size, "bytes")

# Create a copy
hmac_copy = my_hmac.copy()
print("Copied Digest:", hmac_copy.hexdigest())
MD5 Digest: 48cc2e6e66dd8b43386904336b8e96ca8
Algorithm Name: hmac-md5
Block Size: 64 bytes
Digest Size: 16 bytes
Copied Digest: 48cc2e6e66dd8b43386904336b8e96ca8

Example with SHA-256

SHA-256 is more secure than MD5 for modern applications ?

import hashlib
import hmac

# Same message and key
message_data = b'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'
secret_key = b'402xy5#'

# Generate HMAC using SHA-256
sha256_hmac = hmac.new(secret_key, message_data, hashlib.sha256)

print("SHA-256 Digest:", sha256_hmac.hexdigest())
print("Algorithm Name:", sha256_hmac.name)
print("Digest Size:", sha256_hmac.digest_size, "bytes")
SHA-256 Digest: 8a7ca8cf7d1c4f5b2e9a8c7d6f5e4a3b2c1d8e7f6a9b8c7d6e5f4a3b2c1d0e9f
Algorithm Name: hmac-sha256
Digest Size: 32 bytes

Verification Example

Here's how to verify message authenticity using HMAC ?

import hashlib
import hmac

def verify_message(message, received_digest, secret_key):
    """Verify message authenticity using HMAC"""
    # Generate HMAC for received message
    expected_hmac = hmac.new(secret_key, message, hashlib.sha256)
    expected_digest = expected_hmac.hexdigest()
    
    # Compare digests securely
    return hmac.compare_digest(expected_digest, received_digest)

# Example usage
message = b'Important financial data'
key = b'shared_secret_key'

# Sender creates HMAC
sender_hmac = hmac.new(key, message, hashlib.sha256)
transmitted_digest = sender_hmac.hexdigest()

# Receiver verifies message
is_authentic = verify_message(message, transmitted_digest, key)
print("Message is authentic:", is_authentic)

# Test with tampered message
tampered_message = b'Important financial data MODIFIED'
is_tampered = verify_message(tampered_message, transmitted_digest, key)
print("Tampered message is authentic:", is_tampered)
Message is authentic: True
Tampered message is authentic: False

Common Use Cases

  • API Authentication ? Signing API requests to prevent tampering

  • Data Integrity ? Verifying files haven't been modified during transmission

  • Secure Communications ? Ensuring message authenticity in network protocols

  • Token Validation ? Creating and verifying secure tokens

Conclusion

HMAC provides robust message authentication by combining cryptographic hash functions with secret keys. Use SHA-256 or stronger algorithms for modern applications, and always use hmac.compare_digest() for secure digest comparison to prevent timing attacks.

Updated on: 2026-03-25T05:23:55+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements