easy +10 pts

Verify HMAC signature

Implement HMAC-SHA256 signature verification using constant-time comparison.

Write a function `verify_hmac(message: str, key: str, signature: str) -> bool` that returns `True` if `signature` is a valid HMAC-SHA256 of `message` using `key`, and `False` otherwise. The signature is provided as a lowercase hexadecimal string of length 64. Use `hmac.new` with the SHA256 digest and compute the digest as a hex string. Compare the computed hex digest against the provided signature using `hmac.compare_digest` on the two hex strings to avoid timing attacks. The function must work for any strings (including empty strings) and must never raise an exception for any input that satisfies the constraints.

Constraints

Input strings may be empty or non-empty and consist of ASCII characters. Length of message and key is at most 1000 characters. Signature is exactly 64 lowercase hex characters (0-9, a-f). The function must return a boolean and must not raise exceptions.

Example

>>> verify_hmac('hello', 'secret', '88aab3ede8d5ad2a1c4a6a5e6a5e6a5e6a5e6a5e6a5e6a5e6a5e6a5e6a5e6a5e')
False
>>> verify_hmac('hello', 'secret', 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef')
False
>>> verify_hmac('hello', 'secret', '88aab3ede8d5ad2a1c4a6a5e6a5e6a5e6a5e6a5e6a5e6a5e6a5e6a5e6a5e6a5e')
False
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use `hmac.new(key.encode(), message.encode(), hashlib.sha256).hexdigest()` to compute the expected signature.
Compare the computed hex digest with the provided signature using `hmac.compare_digest` on the two strings.
Remember to encode the message and key to bytes before passing to hmac.new.
The signature length is always 64, but the function should still work correctly even if the signature length is not 64 (just return False).
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.