Skip to content

Instantly share code, notes, and snippets.

@ph4r05
Last active November 11, 2021 09:13
Show Gist options
  • Save ph4r05/441faa20680b3fc1e6009c92435b5139 to your computer and use it in GitHub Desktop.
Save ph4r05/441faa20680b3fc1e6009c92435b5139 to your computer and use it in GitHub Desktop.
Constant time array equality check in java
package ct;
public class CT {
/**
* Constant time array equals check.
* If the lengths do not match the function returns false immediately.
* @param a array A
* @param b array B
* @return true if arrays are equal on defined intervals
*/
public static boolean isEqual(byte[] a, byte[] b) {
if (a.length != b.length) {
return false;
}
byte result = 0;
for (byte i = 0; i < a.length; i++) {
result |= (byte)(a[i] ^ b[i]);
}
return result == 0;
}
/**
* Constant time array equals check.
* Exception behavior consistent with
* <a href="https://docs.oracle.com/javacard/3.0.5/api/javacard/framework/Util.html#arrayCompare(byte[],%20short,%20byte[],%20short,%20short)">Util.arrayCompare()</a>
*
* @param a array A
* @param offsetA offset to start equal check from for array A
* @param b array B
* @param offsetB offset to start equal check from for array B
* @param length length of the compared sequence
* @return true if arrays are equal on defined intervals
*/
public static boolean isEqual(byte[] a, short offsetA, byte[] b, short offsetB, short length) {
if (a == null || b == null){
throw new NullPointerException();
}
if (offsetA < 0 || offsetB < 0 || length < 0){
throw new ArrayIndexOutOfBoundsException();
}
if ((short)(offsetA + length) > a.length || (short)(offsetB + length) > b.length) {
throw new ArrayIndexOutOfBoundsException();
}
byte result = 0;
for (byte i = 0; i < length; i++) {
result |= (byte)(a[(short)(offsetA + i)] ^ b[(short)(offsetB + i)]);
}
return result == 0;
}
}
@qb20nh
Copy link

qb20nh commented Nov 11, 2021

Is it not necessary that we always check against dummy array and return false when lenghts are diffrent?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment