Skip to content

Commit abdd852

Browse files
committed
Improved constant time equals and add mention in readme
1 parent 00a6998 commit abdd852

File tree

3 files changed

+11
-3
lines changed

3 files changed

+11
-3
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,8 @@ Bytes.wrap(array).entropy();
376376
Of course all standard Java Object methods are implemented including:
377377
`hashCode()`, `equals()`, `toString()` as well as it being
378378
[`Comparable`](https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html).
379+
In addition there is a constant time `equalsConstantTime()` method, see [here](https://codahale.com/a-lesson-in-timing-attacks/) why this
380+
might be useful.
379381

380382
The `toString()` methods only shows the length and a preview of maximal 8 bytes:
381383

src/main/java/at/favre/lib/bytes/Bytes.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1627,6 +1627,8 @@ public boolean equals(byte[] anotherArray) {
16271627
* will not break on the first mismatch. This method is useful to prevent some side-channel attacks,
16281628
* but is slower on average.
16291629
*
1630+
* This implementation uses the algorithm suggested in https://codahale.com/a-lesson-in-timing-attacks/
1631+
*
16301632
* @param anotherArray to compare with
16311633
* @return true if {@link Arrays#equals(byte[], byte[])} returns true on given and internal array
16321634
*/

src/main/java/at/favre/lib/bytes/Util.java

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -433,13 +433,17 @@ static boolean equals(byte[] obj, Byte[] anotherArray) {
433433
return true;
434434
}
435435

436+
/**
437+
* See https://codahale.com/a-lesson-in-timing-attacks/
438+
*/
436439
static boolean constantTimeEquals(byte[] obj, byte[] anotherArray) {
437440
if (anotherArray == null || obj.length != anotherArray.length) return false;
438-
boolean result = true;
441+
442+
int result = 0;
439443
for (int i = 0; i < obj.length; i++) {
440-
result &= obj[i] == anotherArray[i];
444+
result |= obj[i] ^ anotherArray[i];
441445
}
442-
return result;
446+
return result == 0;
443447
}
444448

445449
/*

0 commit comments

Comments
 (0)