easy +10 pts

Verify HMAC signature

Check HMAC-SHA256 signatures with constant-time comparison.

Write a function `verify_hmac(message: str, key: str, signature: str) -> bool` that returns `True` if the provided `signature` is a valid HMAC-SHA256 digest of the `message` using the given `key`. The signature is expected to be a 64-character lowercase hexadecimal string. If `signature` is not a string of exactly 64 lowercase hex characters, the function should return `False`. Otherwise, compute the HMAC-SHA256 digest using the provided `key` and `message` and compare the result with the provided signature using a constant-time comparison (e.g., `hmac.compare_digest`).

Constraints

- `message` and `key` are non-empty strings (length ≤ 1000). - `signature` is a string; if it is not exactly 64 lowercase hexadecimal characters, return `False`. - The function should not raise exceptions for invalid input. - Time complexity: O(len(message)). Space: O(1).

Example

>>> verify_hmac('hello', 'secret', '88aab3ede8d5ad9a1b8e8f3b8b2c4e5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a0b1c')
True
>>> verify_hmac('hello', 'secret', '0000000000000000000000000000000000000000000000000000000000000000')
False
>>> verify_hmac('hello', 'secret', 'nothex')
False
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Compute the expected HMAC using hmac.new(key.encode(), message.encode(), hashlib.sha256).hexdigest().
Use hmac.compare_digest for constant-time string comparison.
Validate the signature format: exactly 64 characters, all lowercase hex digits.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.