https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Helpers/Crypto.cs#L159
// Compares two byte arrays for equality. The method is specifically written so that the loop is not optimized.
[MethodImpl(MethodImplOptions.NoOptimization)]
private static bool ByteArraysEqual(byte[] a, byte[] b)
{
if (ReferenceEquals(a, b))
{
return true;
}
if (a == null || b == null || a.Length != b.Length)
{
return false;
}
bool areSame = true;
for (int i = 0; i < a.Length; i++)
{
areSame &= (a[i] == b[i]);
}
return areSame;
}
It's written that way in order to preclude the possibility of timing attacks.
If the code had the obvious early-out optimization, it would "leak" information about the result of the comparison via the time taken to execute it - equal arrays would take longer to compare.
If used as part of an implementation of crypto-related code, the leaked information could be helpful to an attacker trying to crack it.
It seems like an unlikely method at first glance, but this is a real threat - see this paper for an example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With