CSRF attacks and token protection in PHP - Time & Space Complexity
We want to understand how the time it takes to check CSRF tokens grows as the number of requests or tokens increases.
How does the token verification process scale when handling many requests?
Analyze the time complexity of the following PHP code snippet for CSRF token verification.
// Assume session token is stored
session_start();
function verifyCsrfToken($token) {
if (!isset($_SESSION['csrf_token'])) {
return false;
}
return hash_equals($_SESSION['csrf_token'], $token);
}
$userToken = $_POST['csrf_token'] ?? '';
if (verifyCsrfToken($userToken)) {
// Proceed with request
} else {
// Reject request
}
This code checks if the CSRF token sent by the user matches the one stored in the session.
Look for operations that repeat or take time depending on input size.
- Primary operation: Comparing two fixed-length strings with
hash_equals. - How many times: Once per request, no loops or recursion involved.
The token comparison always takes about the same time because tokens have fixed length.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 requests | 10 token comparisons |
| 100 requests | 100 token comparisons |
| 1000 requests | 1000 token comparisons |
Pattern observation: The time grows linearly with the number of requests, but each check is very fast and constant time.
Time Complexity: O(1)
This means each token check takes the same small amount of time, no matter what.
[X] Wrong: "Checking CSRF tokens gets slower as more users use the site."
[OK] Correct: Each token check is independent and constant time, so more users do not slow down a single check.
Understanding how security checks like CSRF token verification scale helps you write safe and efficient web applications.
What if the token was stored in a database and you had to search for it each time? How would the time complexity change?