I want to implement a String comparison function that doesn’t take a different amount of time depending on the number of characters that match or the position of the first mismatch. I assume there must be a library out there somewhere that provides this, but I was unable to find it via a quick search.
So far, the best idea I’ve got is to sum the XOR of each character and return whether or not the sum is 0. However, I’m pretty sure this wouldn’t work so well with Unicode. I also have a vague concern that HotSpot would do some optimizations that would change my constant-time property, but I can’t think of a specific optimization that would do this off the top of my head.
Thanks.
UPDATE: Sorry, I don’t believe I was clear. I’m not looking for O(1), I’m looking for something that won’t leak timing information. This would be used to compare hashed password values, and if the time it took to compare was different based on where the first mismatch occurred, that would be leaking information to an attacker.
I see two immediate possibilities for not leaking password-related information in timing:
1/ Pad both the password string and candidate string out to 1K, with a known, fixed character (like
A). Then run the following (pseudo-code):That way, you’re always taking the same amount of loops to do the comparison regardless of where it matches.
There’s no need to muck about with
xorsince you can still do a simple comparison, but without exiting the loop early.Just set the match flag to false if a mismatch is found and keep going. Once the loop exits (taking the same time regardless of size or content of password and candidate), then check whether it matched.
2/ Just add a large (relative to the normal comparison time) but slightly random delay at the end of the comparison. For example, a random value between 0.9 and 1.1 seconds. The time taken for the comparison should be swamped by the delay and the randomness should fully mask any information leakage (unless your randomness algorithm leaks information, of course).
That also has the added advantage of preventing brute force attacks since a password check takes at least about a second.