6

According to this post, Dominick Baier was comparing two HMACSHA256 signatures and was leaking timing information upon an unsuccessful comparison.

When working with .NET crypto classes, when should one adopt a similar approach, and sleep for a random amount of time? What amount of time is sufficient?

[MethodImpl(MethodImplOptions.NoOptimization)]
public static bool IsEqual(string s1, string s2)
{
    if (s1 == null && s2 == null)
    {
        return true;
    }

    if (s1 == null || s2 == null)
    {
        return false;
    }

    if (s1.Length != s2.Length)
    {
        return false;
    }

    var s1chars = s1.ToCharArray();
    var s2chars = s2.ToCharArray();

    int hits = 0;
    for (int i = 0; i < s1.Length; i++)
    {
        if (s1chars[i].Equals(s2chars[i]))
        {
            hits += 2;
        }
        else
        {
            hits += 1;
        }
    }

    bool same = (hits == s1.Length * 2);

    if (!same)
    {
        var rnd = new CryptoRandom();
        Thread.Sleep(rnd.Next(0, 10));
    }

    return same;
}
makerofthings7
  • 50,488
  • 54
  • 253
  • 542

1 Answers1

7

Sleeping a random amount of time doesn't totally stop the information leak: if the attack can be repeated, the random part will average out to a constant. Instead, you should make sure that the operation always takes the same amount of time.

Wim Coenen
  • 186
  • 5