Take the 2-minute tour ×
Information Security Stack Exchange is a question and answer site for Information security professionals. It's 100% free, no registration required.

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;
}
share|improve this question

1 Answer 1

up vote 6 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.