PythiloLesson 8 of 8 · progress kept in this browser

Authenticate exact bytes with HMAC

An HMAC binds a byte sequence to a shared secret key. A verifier recomputes the tag with the same key and compares it with the received tag. Changing the message or key changes the result. The message itself remains readable.

Both sides must agree on the exact bytes, including encoding, whitespace and field order when serializing structured data. Use compare_digest for tag comparison instead of building a custom character loop. This exercise authenticates a small local byte string; a full protocol must additionally define its own key handling and message freshness contract.

import hashlib, hmac
key, message = b"demo-key", b"hello"
tag = hmac.new(key, message,
               hashlib.sha256).hexdigest()
expected = hmac.new(key, message,
                    hashlib.sha256).hexdigest()
print(hmac.compare_digest(tag, expected))
Your task

Implement sign_message(key,message) returning a SHA-256 HMAC hex string, and verify_message(key,message,signature) using compare_digest. All inputs except signature are bytes. A changed key, message or signature must fail verification.

All lessons