Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this loop intentionally not optimized?

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;
}
like image 651
Kenneth Ito Avatar asked Nov 30 '17 00:11

Kenneth Ito


Video Answer


1 Answers

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.

like image 115
Blorgbeard Avatar answered Sep 19 '22 20:09

Blorgbeard