Java: Why is this Equal-String function protected against timing attacks

607 Views Asked by At

On Stackoverflow I found the following String-Equal-Function, which should be resistent against timing attacks.

private boolean equalSignatureString(String signature1, String signature2) {
    if(signature1.length() != signature2.length()) {
        return false;
    }

    byte[] signature1Byte = signature1.getBytes();
    byte[] signature2Byte = signature2.getBytes();

    int result = 0;
    for(int i = 0; i < signature1Byte.length; i++) {
        result |= signature1Byte[i] ^ signature2Byte[i];
    }
    return result == 0;
}

I wonder why this is save against timing-attacks. I understand, that we compare the complete length of the strings even if they doesn't match after the first char (which could be a point for timing attacks). But if signature1Byte[i] is not equal to signature2Byte[i] then we have to add +1 to result otherwise not. Doesn't the "add +1" takes also longer than "just proceed to the next loop"? Wouldn't it be better to count up an other variable (which is useless) when the bytes are equal, so we always have the same running time?

1

There are 1 best solutions below

0
On

While we you could possible do that, implementation which use if not only slower, but may have unpredictable problem because of optimization.

JIT may throw away your unused variable and CPU branch prediction may also influence on how long each branch is executed.