Question

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

Was it helpful?

Solution

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.

OTHER TIPS

Just adding to this in hopes to save someone the headache I went through.

In the case of .Net Membership Provider, make sure you have the setting in your web.config or app.config. Else it will automatically generate its own key... crap out on authentication, and then belligerently laugh at you in the end.

You need a Key for HMACSHA256. The key will be random if it is not passed into the constructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top