Then it would always take the same amount of time to return `true/false`, even if you knew this value earlier in the loop.
Then it would always take the same amount of time to return `true/false`, even if you knew this value earlier in the loop.
Let’s say you have a bool, $is_match then whenever two chars of the string don’t match you write false to it.
It takes slightly longer to write false than do nothing. You’re still leaking the total number of matching characters.
I think speculative execution on the CPU would amplify this effect. For example:
aaaaaaaaa != ccccccccc will be much faster than ababababa != aaaaaaaaa because in the first example the cpu will correctly guess and speculatively execute that the two characters are different. They were different last time. They’ll probably be different again.
For each byte index i:
x[i] = a[i] XOR b[i]
return sum(x) == 0
So it’ll be faster if: most characters match, most characters don’t match or there are runs of matching characters.
Have a read of this: https://stackoverflow.com/questions/11227809/why-is-processi...
// Throw an error if inputKey is not correct.
// inputKey and correctKey are both strings
function checkApiKey(inputKey, correctKey) {
var isMatch = true;
for (var i = 0; i < inputKey.length; i++)
if (inputKey.charAt(i) !== correctKey.charAt(i)) {
isMatch = false;
}
}
if (!isMatch) {
throw new Error("wrong key");
}
}
So what I meant is, don't return early when isMatch = false, instead walk the entire key regardless.That instruction is executed conditionally, you can time it.
Maybe eliminate the if completely an do something like this
...
for (var i = 0; i < inputKey.length; i++)
isMatch = isMatch && (inputKey.charAt(i) !== correctKey.charAt(i)
}
...I'm assuming the function would take the same amount of time to run regardless for which value of "i" the write occurs at. Wouldn't that then protect the attack vector of enumerating keys and checking the time?
As in, the only input that would cause the write to `isMatch` to be skipped would be the correct key, in which case you don't need to brute force the solution.