PHP
Intermediate
Estimated Duration: 20 min
PHP 8.2: Constant-Time Cryptographic Token Verification
Secure your API gateway against timing attacks using constant-time hash comparisons and Bearer parsing.
Preventing Timing Attacks in Authentication
In standard string comparisons (
$a === $b), PHP returns false as soon as the first non-matching byte is found. An attacker measuring latency with microsecond accuracy can determine which characters are correct one byte at a time.PHP provides
hash_equals() which compares strings in constant time regardless of where a mismatch occurs.In this lesson, you will build a production-grade API authentication validator that safely parses
Authorization: Bearer sfx_live_... headers.
Target Output
{"valid":true,"token":"sfx_live_99482abc..."}
Need a Hint?
- Use preg_match('/^Bearer\s+(sfx_live_\w+)$/i', $authHeader, $matches)
- Compute hash('sha256', $token)
- Compare with hash_equals($knownHash, $computedHash)
solution.php
Terminal Output
Ready
Click "Run Code & Test" to execute your solution.