Check HMAC-SHA1 without key in C#

1.9k views Asked by At

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?
2

There are 2 answers

0
Alexey Shcherbak On BEST ANSWER

Yes, because you are using parameterless constructor to build HMACSHA1 instance, and MSDN says

HMACSHA1() - Initializes a new instance of the HMACSHA1 class with a randomly generated key.

Just add some constant key and you'll get same hash every time. e.g.

var hmacSha = new HMACSHA1(Encoding.UTF8.GetBytes("yourConstantKey"));

And answering your questions:

  1. Yes, use same key for 2 generations.
  2. Yes.
  3. It generates random key for you
0
Jon Skeet On

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);