Password hashing with password_hash in PHP - Time & Space Complexity
When we use password_hash in PHP, it takes some time to turn a password into a secure hash.
We want to understand how the time it takes changes as the password or settings change.
Analyze the time complexity of the following code snippet.
$password = 'mysecretpassword';
$hash = password_hash($password, PASSWORD_DEFAULT);
echo $hash;
This code creates a secure hash from a password using PHP's built-in function.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The hashing algorithm runs multiple internal rounds to secure the password.
- How many times: The number of rounds depends on the algorithm and its cost setting, repeating the hashing steps many times.
The time to hash grows mainly with the number of rounds, not the password length.
| Input Size (Rounds) | Approx. Operations |
|---|---|
| 10 | 10 hashing steps |
| 20 | 20 hashing steps |
| 50 | 50 hashing steps |
Pattern observation: Doubling the rounds roughly doubles the time, while password length has little effect.
Time Complexity: O(r)
This means the time grows linearly with the number of hashing rounds set in the algorithm.
[X] Wrong: "Hashing time depends mostly on the password length."
[OK] Correct: The hashing time depends mainly on the number of rounds, not the password length, which is usually short and fixed.
Understanding how hashing time grows helps you explain security trade-offs clearly and shows you know how to balance safety and performance.
"What if we increased the cost parameter in password_hash? How would the time complexity change?"