Check HMAC SHA1 without key in C#

I am generating HMAC-SHA1 without key in C# and it returns every time different hash for same value, how can I match hashes,

My code is https://dotnetfiddle.net/3a3tiP

  • is it possible or not to match these hashes?
  • I think HMAC-SHA1 not possible without key Am I right?
  • If above 'Yes' then why C# allow to generate without key and how is it doing?
Jon Skeet
people
quotationmark

From the documentation of HMACSHA1:

A Hash-based Message Authentication Code (HMAC) can be used to determine whether a message sent over an insecure channel has been tampered with, provided that the sender and receiver share a secret key.

So yes, you need a key. If you don't specify a key, one will be generated for you, and you can fetch it with the Key property afterwards (e.g. to store it). Or you can specify it in the constructor, or set the Key property, either because you've received it from the other party, or because you want to reuse a previously-generated key.

If you hash the same data using the same key, you should get the same hash as a result.

As noted in comments, you should not then convert the HMAC to a string using Encoding.GetString, because it's arbitrary binary data - it's not encoded text. The simplest approach is probably to use base64 instead:

string base64Hmac = Convert.ToBase64String(hmac);

people

See more on this question at Stackoverflow