Skip to content

Instantly share code, notes, and snippets.

@pjan
Created May 9, 2015 13:49
Show Gist options
  • Save pjan/e69545b8922679be66c6 to your computer and use it in GitHub Desktop.
Save pjan/e69545b8922679be66c6 to your computer and use it in GitHub Desktop.
Comparison of strings in a time attack safe way
def safeEquals(a: String, b: String) = {
val a_bytes = a.getBytes
val b_bytes = b.getBytes
if (a_bytes.length != b_bytes.length) {
false
}
else {
a_bytes.zip(b_bytes).foldLeft(0){ (acc, t) => acc + (t._1 ^ t._2) } == 0
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment