Kenneth Ito
Kenneth Ito

Reputation: 5261

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;
}

Upvotes: 12

Views: 198

Answers (1)

Blorgbeard
Blorgbeard

Reputation: 103585

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.

Upvotes: 10

Related Questions