Skip to content

Commit 9a62750

Browse files
committed
Refactor constant-time comparison
1 parent 4c6811e commit 9a62750

File tree

2 files changed

+33
-2
lines changed

2 files changed

+33
-2
lines changed

core/src/main/java/org/bouncycastle/pqc/crypto/hqc/HQCEngine.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,12 +179,12 @@ public int decaps(byte[] ss, byte[] ct, byte[] sk)
179179
pkeEncrypt(cKemPrimeU64, cKemPrimeV64, sk, mPrime, kThetaPrime, 32);
180180
hashGJ(kBar, 256, hashEkKem, sk, pkSize + SEED_BYTES, K_BYTE, ct, 0, ct.length, (byte)3);
181181

182-
if (!Arrays.constantTimeAreEqual(u64, cKemPrimeU64))
182+
if (!Arrays.constantTimeAreEqual(N_BYTE_64, u64, 0, cKemPrimeU64, 0))
183183
{
184184
result = 1;
185185
}
186186

187-
if (!Arrays.constantTimeAreEqual(v64, cKemPrimeV64))
187+
if (!Arrays.constantTimeAreEqual(N_BYTE_64, v64, 0, cKemPrimeV64, 0))
188188
{
189189
result = 1;
190190
}

core/src/main/java/org/bouncycastle/util/Arrays.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,37 @@ public static boolean constantTimeAreEqual(int len, byte[] a, int aOff, byte[] b
149149
return 0 == d;
150150
}
151151

152+
public static boolean constantTimeAreEqual(int len, long[] a, int aOff, long[] b, int bOff)
153+
{
154+
if (null == a)
155+
{
156+
throw new NullPointerException("'a' cannot be null");
157+
}
158+
if (null == b)
159+
{
160+
throw new NullPointerException("'b' cannot be null");
161+
}
162+
if (len < 0)
163+
{
164+
throw new IllegalArgumentException("'len' cannot be negative");
165+
}
166+
if (aOff > (a.length - len))
167+
{
168+
throw new IndexOutOfBoundsException("'aOff' value invalid for specified length");
169+
}
170+
if (bOff > (b.length - len))
171+
{
172+
throw new IndexOutOfBoundsException("'bOff' value invalid for specified length");
173+
}
174+
175+
long d = 0;
176+
for (int i = 0; i < len; ++i)
177+
{
178+
d |= (a[aOff + i] ^ b[bOff + i]);
179+
}
180+
return 0L == d;
181+
}
182+
152183
/**
153184
* A constant time equals comparison - does not terminate early if
154185
* comparison fails. For best results always pass the expected value

0 commit comments

Comments
 (0)