Back
+30 XP
Concept

Constant-Time Password Hash Verification

Evaluating secret tokens using standard string equality (a == b) exits early on the first mismatched byte. Attackers measure microsecond execution latency to deduce passwords character by character. The hmac.compare_digest function compares every byte in strictly constant time.

python
import hmac

# Constant-time comparison:
is_valid = hmac.compare_digest(provided_token, secret_token)

# Constant-Time Password Hash Verification When an API checks an authorization token like `if request.token == SECRET_TOKEN:`, Python compares strings character by character from left to right. The millisecond it finds a mismatch, it exits immediately and returns `False`. ⏱️🛡️ This creates a devastating **Side-Channel Timing Attack**: - If the first character of the attacker's guess is wrong, the comparison aborts after 1 comparison. - If the first character is correct, the comparison tests the second character, taking 2 nanoseconds longer. By averaging thousands of network probes, an attacker can determine the correct password character by character. Python's `hmac.compare_digest()` guarantees **constant-time execution**: it always compares every single byte regardless of where differences occur. ```python import hmac # Compares all bytes at fixed duration: valid = hmac.compare_digest(user_input.encode(), expected_token.encode()) ``` ## Pop Quiz How does an attacker exploit standard string equality (`a == b`) in an authentication endpoint? - [ ] By executing timing attacks that measure nanosecond response delays to guess credentials byte by byte. - [ ] Standard equality checks dump password strings into the Linux kernel syslog. - [ ] By sending Unicode byte-order marks that overflow the CPU ALU registers. - [ ] Because standard string equality automatically converts passwords to plaintext cookies. ## Real-World Challenge Implement `safe_token_verify(provided: str, secret: str) -> bool`. - Convert both strings to UTF-8 bytes. - Use `hmac.compare_digest` to verify equality. - Prevent timing leak side-channels on differing lengths or content. <details> <summary>Solution</summary> ```python import hmac def safe_token_verify(provided: str, secret: str) -> bool: if not isinstance(provided, str) or not isinstance(secret, str): return False # Encode to bytes to avoid Unicode normalization timing variance provided_bytes = provided.encode("utf-8") secret_bytes = secret.encode("utf-8") return hmac.compare_digest(provided_bytes, secret_bytes) # Verification master_key = "production_super_secret_api_key_8888" # 1. Matching token assert safe_token_verify(master_key, master_key) is True # 2. Mismatched token assert safe_token_verify("wrong_key", master_key) is False # 3. Partially matching prefix assert safe_token_verify("production_super_secret_api_key_9999", master_key) is False ``` </details>