tozny/java-aes-crypto

constantTimeEq not constant

jedrivisser opened this issue · 3 comments

Hi, the constantTimeEq starts with:

if (a.length != b.length) {
return false;
}

this kind of makes it not equal time or am I missing something?

If I remember correctly, the correct way to handle this is with fake comparissons, something like:

int result = 0;
if (a.length != b.length) {
for (int i = 0; i < a.length; i++) {
result |= a[i] ^ a[i];
}
return false;
}

It is not a problem if the lengths are different: we aren't assuming that the length is hard to guess.

Even if you added fake comparisons, you'd still be able to guess the length, because you could just try increasing b.length until it exceeds a.length. This will add in fake comparisons, which will cause a noticeable increase in time, and so you will then know a.length.

See, for example, https://golang.org/src/crypto/subtle/constant_time.go

Also, there's a decent chance that the compiler would just optimize out the a[i] ^ a[i] operation, and remove the fake comparisons altogether. Any time we do constant time comparison, we have to be careful about how smart the compiler is. :)

true, thanks for the response

Thanks for the suggestion — keep 'em coming. I definitely had the exact same thought the first time I saw it. :)