Skip to content

Commit 1a38980

Browse files
committed
Constant-time byte[] comparison
1 parent be161ee commit 1a38980

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

src/net/i2p/crypto/eddsa/Utils.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,18 @@ public static int equal(int b, int c) {
1818
return (result ^ 0x01) & 0x01;
1919
}
2020

21+
/**
22+
* Constant-time byte[] comparison.
23+
* @return 1 if b and c are equal, 0 otherwise.
24+
*/
25+
public static int equal(byte[] b, byte[] c) {
26+
int result = 0;
27+
for (int i = 0; i < 32; i++) {
28+
result |= b[i] ^ c[i];
29+
}
30+
return ~equal(result, 0) & 0x01;
31+
}
32+
2133
/**
2234
* Constant-time determine if byte is negative.
2335
* @param b the byte to check.

src/net/i2p/crypto/eddsa/math/ed25519/Ed25519FieldElement.java

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package net.i2p.crypto.eddsa.math.ed25519;
22

33
import net.i2p.crypto.eddsa.TestUtils;
4+
import net.i2p.crypto.eddsa.Utils;
45
import net.i2p.crypto.eddsa.math.Field;
56
import net.i2p.crypto.eddsa.math.FieldElement;
67

@@ -26,11 +27,7 @@ public Ed25519FieldElement(Field f, int[] t) {
2627

2728
public boolean isNonZero() {
2829
byte[] s = toByteArray();
29-
int result = 0;
30-
for (int i = 0; i < 32; i++) {
31-
result |= s[i] ^ zero[i];
32-
}
33-
return result != 0;
30+
return Utils.equal(s, zero) == 1;
3431
}
3532

3633
/**

0 commit comments

Comments
 (0)