($i + 1) % $safeLen
Even so, I guess the only way to eliminate timing attacks would be to write a set of primitive operations (XOR, AND, OR, ORD,...) which are constant-time (on the supported hardware platform) and only use those wherever the private information is handled. Is this possible to do? Are there any attempts at this?Is there a reason for using the attacker's string rather than the valid string? Edit: it doesn't seem to me that using the valid string would leak its length unless the attacker knew quite a lot about the target machine.
It sounds like you are skeptical that timing attacks can be practically exploited. This is a reasonable skepticism that most people go through on initially learning about them. Unfortunately, there are in fact working exploits for this sort of thing.
As I understand it, the correct thing to do is to derive a sleep time from hashing the request content, along with some secret. This makes the delay "random" from the attackers point of view, but still deterministic and therefore impossible to filter out.
Note: I am not a security person, just an interested bystander. Take this half-remembered advice with a pinch of salt.
2. Less than you'd think. e.g., the total count of all 1 and 2 and 3 digit numbers is only 11% of the count of 4 digit numbers. (And that stat gets worse with just lower case letters.) Searching all shorter passwords ends up being an insignificant amount of time compared to searching all correctly sized passwords.
Even that is harder than it looks.
For example, a common way of doing a constant time string compare is:
i.e. get the character to compare mod the length, so you wrap around if the length of the two strings is not the same.Unfortunately the mod operator does not take a constant time on a CPU! If the result is evenly divisible it's faster.
So even in assembly you might not be able to protect from a timing attack. Even if you check your current CPU a new one might be different.
(In this case a better way to do the compare is if the strings are not the same length, compare the attackers string against itself, and then return false.)