Skip to content

Instantly share code, notes, and snippets.

@adrianstevens
Created January 7, 2016 19:21
Show Gist options
  • Save adrianstevens/b053ec17cfc5ca868e71 to your computer and use it in GitHub Desktop.
Save adrianstevens/b053ec17cfc5ca868e71 to your computer and use it in GitHub Desktop.
C# Slow equals
/// <summary>
/// Compares two byte arrays in length-constant time. This comparison
/// method is used so that password hashes cannot be extracted from
/// on-line systems using a timing attack and then attacked off-line.
/// </summary>
/// <param name="a">The first byte array.</param>
/// <param name="b">The second byte array.</param>
/// <returns>True if both byte arrays are equal. False otherwise.</returns>
private static bool SlowEquals(byte[] a, byte[] b)
{
uint diff = (uint)a.Length ^ (uint)b.Length;
for (int i = 0; i < a.Length && i < b.Length; i++)
diff |= (uint)(a[i] ^ b[i]);
return diff == 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment