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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With