Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ComputeHash not acting deterministically?

I've run into an interesting issue.. It seems that ComputeHash() for a "HMACSHA256" hash is not behaving deterministically.. if I create two instances of HashAlgorithm using HashAlgorithm.Create("HMACSHA256").. And run ComputeHash, I get two different results.. below is an example static class that exhibiting this behavior.

internal static string HashPassword(byte[] bAll)
{
    using (HashAlgorithm s = HashAlgorithm.Create("HMACSHA256"))
    {
        return Convert.ToBase64String(s.ComputeHash(bAll));
    }
}

I've also tried to make the call non static (actually it started non static, and I have double and triple and quadrudruple checked my input array.. its absolutely the same on each call.. I've even done stuff in the immidiate window like :

Convert.ToBase64String(HashAlgorithm.Create("HMACSHA256").ComputeHash(bAll)

And running that twice in the immidiates window via a breakpoint in the method returns two different hashes..

I know Hash is suppose to be deterministic.. So what gives? is something going on with running in a debugger? Or any other ideas? really this is just two weird for words right now :-P..

Thanks Josh

like image 871
Josh Handel Avatar asked Jul 06 '10 13:07

Josh Handel


1 Answers

HMAC is a keyed hash. I don't see the key in your example code.

HashAlgorithm.Create("HMACSHA256") creates a HashAlgorithm instance, so it doesn't know anything about a key. It probably just calls this HMACSHA256 Constructor:

public HMACSHA256()

Initializes a new instance of the HMACSHA256 class with a randomly generated key.

You want this constructor:

public HMACSHA256(byte[] key)

Initializes a new instance of the HMACSHA256 class with the specified key data.

If you don't want to to hard-code the HMAC algorithm, you can use KeyedHashAlgorithm.Create and supply a specific key by setting the KeyedHashAlgorithm.Key property.

If you don't want to use a key, then use a non-keyed hash like SHA256.

like image 154
dtb Avatar answered Oct 04 '22 18:10

dtb