Skip to content

Instantly share code, notes, and snippets.

@mpellegrini
Created March 26, 2014 18:08
Show Gist options
  • Save mpellegrini/9789595 to your computer and use it in GitHub Desktop.
Save mpellegrini/9789595 to your computer and use it in GitHub Desktop.
A Lesson In Timing Attacks (see http://codahale.com/a-lesson-in-timing-attacks/)
// Better
public static boolean isEqual(byte[] a, byte[] b) {
if (a.length != b.length) {
return false;
}
int result = 0;
for (int i = 0; i < a.length; i++) {
result |= a[i] ^ b[i]
}
return result == 0;
}
// worse
public static boolean isEqual(byte digesta[], byte digestb[]) {
if (digesta.length != digestb.length)
return false;
for (int i = 0; i < digesta.length; i++) {
if (digesta[i] != digestb[i]) {
return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment