Skip to content

Commit 8253fbe

Browse files
committed
Used the O(1) equals. Moved bytesToHex function to Utils
2 parents 732e73f + 1a38980 commit 8253fbe

File tree

2 files changed

+34
-12
lines changed

2 files changed

+34
-12
lines changed

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

Lines changed: 30 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.
@@ -51,4 +63,22 @@ public static byte[] hexToBytes(String s) {
5163
}
5264
return data;
5365
}
66+
67+
/**
68+
* Converts bytes to a hex string.
69+
* @param raw the byte[] to be converted.
70+
* @return the hex representation as a string.
71+
*/
72+
public static String bytesToHex(byte[] raw) {
73+
if ( raw == null ) {
74+
return null;
75+
}
76+
final StringBuilder hex = new StringBuilder(2 * raw.length);
77+
for (final byte b : raw) {
78+
hex.append(Character.forDigit((b & 0xF0) >> 4, 16))
79+
.append(Character.forDigit((b & 0x0F), 16));
80+
}
81+
return hex.toString();
82+
}
83+
5484
}

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

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

3-
import java.util.Arrays;
4-
5-
import javax.xml.bind.DatatypeConverter;
6-
3+
import net.i2p.crypto.eddsa.Utils;
74
import net.i2p.crypto.eddsa.math.Field;
85
import net.i2p.crypto.eddsa.math.FieldElement;
96

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

3027
public boolean isNonZero() {
3128
byte[] s = toByteArray();
32-
int result = 0;
33-
for (int i = 0; i < 32; i++) {
34-
result |= s[i] ^ zero[i];
35-
}
36-
return result != 0;
29+
return Utils.equal(s, zero) == 1;
3730
}
3831

3932
/**
@@ -962,12 +955,11 @@ public boolean equals(Object obj) {
962955
if (!(obj instanceof Ed25519FieldElement))
963956
return false;
964957
Ed25519FieldElement fe = (Ed25519FieldElement) obj;
965-
// TODO should this be constant time?
966-
return Arrays.equals(toByteArray(), fe.toByteArray());
958+
return 1==Utils.equal(toByteArray(), fe.toByteArray());
967959
}
968960

969961
@Override
970962
public String toString() {
971-
return "[Ed25519FieldElement val="+DatatypeConverter.printHexBinary(toByteArray())+"]";
963+
return "[Ed25519FieldElement val="+Utils.bytesToHex(toByteArray())+"]";
972964
}
973965
}

0 commit comments

Comments
 (0)