Preventing Timing Attacks with hmac.compare_digest
Standard `==` returns `False` immediately upon the first mismatched byte, leaking secrets through timing differences. `hmac.compare_digest` runs in constant time 🛡️.
import hmac
expected_token = "SECRET_TOKEN_XYZ"
user_token = "SECRET_TOKEN_XYZ"
is_valid = hmac.compare_digest(expected_token, user_token)
print(f"Token authenticated safely: {is_valid} 🛡️")
# 112. Preventing Timing Attacks with hmac.compare_digest Standard `==` returns `False` immediately upon the first mismatched byte, leaking secrets through timing differences. `hmac.compare_digest` runs in constant time 🛡️. ```python import hmac expected_token = "SECRET_TOKEN_XYZ" user_token = "SECRET_TOKEN_XYZ" is_valid = hmac.compare_digest(expected_token, user_token) print(f"Token authenticated safely: {is_valid} 🛡️") ``` Always use `hmac.compare_digest` when verifying API keys, HMAC signatures, or password hashes to defeat side-channel timing attacks! 🛡️ --- ### Question Why is standard string equality `token_a == token_b` vulnerable to timing attacks? 🧠 - [ ] a. It exits early on the first mismatched character, leaking the position of matching prefixes 🛡️ - [ ] b. It saves passwords in plaintext in the operating system swap file - [ ] c. It broadcasts strings across the local network - [ ] d. It runs 1,000 times slower than constant-time functions --- ### Challenge Import `hmac`. Use `hmac.compare_digest('valid_key', 'valid_key')`. Print result. 🎯 <details> <summary>Solution</summary> ```python import hmac print(hmac.compare_digest("valid_key", "valid_key")) ``` </details>