From a2595b35e7ec04dec712398ac878755b69ff1c3d Mon Sep 17 00:00:00 2001 From: Michele Balistreri Date: Fri, 25 Nov 2022 10:03:55 +0100 Subject: [PATCH] constant time comparison --- build.gradle | 2 +- buildSrc/build.gradle | 2 +- src/main/java/im/status/keycard/Crypto.java | 36 ++++++++++----------- 3 files changed, 19 insertions(+), 21 deletions(-) diff --git a/build.gradle b/build.gradle index 9e6e663..413d147 100644 --- a/build.gradle +++ b/build.gradle @@ -59,7 +59,7 @@ dependencies { testCompile(files("../jcardsim/jcardsim-3.0.5-SNAPSHOT.jar")) testCompile('org.web3j:core:2.3.1') testCompile('org.bitcoinj:bitcoinj-core:0.14.5') - testCompile('com.github.status-im.status-keycard-java:desktop:64aece4') + testCompile('com.github.status-im.status-keycard-java:desktop:15a61e1') testCompile('org.bouncycastle:bcprov-jdk15on:1.65') testCompile("org.junit.jupiter:junit-jupiter-api:5.1.1") testRuntime("org.junit.jupiter:junit-jupiter-engine:5.1.1") diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle index ec33a25..44786a5 100644 --- a/buildSrc/build.gradle +++ b/buildSrc/build.gradle @@ -4,5 +4,5 @@ repositories { } dependencies { - compile 'com.github.status-im.status-keycard-java:desktop:64aece4' + compile 'com.github.status-im.status-keycard-java:desktop:15a61e1' } \ No newline at end of file diff --git a/src/main/java/im/status/keycard/Crypto.java b/src/main/java/im/status/keycard/Crypto.java index d374241..23fe94a 100644 --- a/src/main/java/im/status/keycard/Crypto.java +++ b/src/main/java/im/status/keycard/Crypto.java @@ -89,11 +89,7 @@ public class Crypto { addm256(output, outOff, data, dataOff, SECP256k1.SECP256K1_R, (short) 0, output, outOff); - if (isZero256(output, outOff)) { - return false; - } - - return true; + return !isZero256(output, outOff); } /** @@ -202,17 +198,22 @@ public class Crypto { * @return the comparison result */ private short ucmp256(byte[] a, short aOff, byte[] b, short bOff) { - short ai, bi; + short gt = 0; + short eq = 1; + for (short i = 0 ; i < 32; i++) { - ai = (short)(a[(short)(aOff + i)] & 0x00ff); - bi = (short)(b[(short)(bOff + i)] & 0x00ff); + short l = (short)(a[(short)(aOff + i)] & 0x00ff); + short r = (short)(b[(short)(bOff + i)] & 0x00ff); + short d = (short)(r - l); + short l_xor_r = (short)(l ^ r); + short l_xor_d = (short)(l ^ d); + short d_xored = (short)(d ^ (short)(l_xor_r & l_xor_d)); - if (ai != bi) { - return (short)(ai - bi); - } + gt |= (d_xored >>> 15) & eq; + eq &= ((short)(l_xor_r - 1) >>> 15); } - return 0; + return (short) ((gt + gt + eq) - 1); } /** @@ -223,16 +224,13 @@ public class Crypto { * @return true if a is 0, false otherwise */ private boolean isZero256(byte[] a, short aOff) { - boolean isZero = true; + byte acc = 0; - for (short i = 0; i < (byte) 32; i++) { - if (a[(short)(aOff + i)] != 0) { - isZero = false; - break; - } + for (short i = 0; i < 32; i++) { + acc |= a[(short)(aOff + i)]; } - return isZero; + return acc == 0; } /**