2

I am trying to replicate a JavaScript hash on C#, but I am getting a different result. The code on JavaScript is:

var key = "35353535353535366363636363",
credentials = "web:web",  
shaObj = new jsSHA(credentials, "ASCII"), 
hash = shaObj.getHMAC(key, "HEX", "SHA-1", "HEX"); // key and generated hash are hex values
alert("Hash: " + hash);

it returns the following hash:

60c9059c9be9bcd092e00eb7f03492fa3259f459

The C# code that I am trying is:

key = "35353535353535366363636363";
string credentials = "web:web";

var encodingCred = new System.Text.ASCIIEncoding();
var encodingKey = new System.Text.ASCIIEncoding();
byte[] keyByte = encodingKey.GetBytes(key);
byte[] credentialsBytes = encodingCred.GetBytes(credentials);
using (var hmacsha1 = new HMACSHA1(keyByte))
{
    byte[] hashmessage = hmacsha1.ComputeHash(credentialsBytes);
    string hash = BitConverter.ToString(hashmessage).Replace("-", string.Empty).ToLower();
    Console.WriteLine("HASH: " + hash);              
} 

it returns the following hash:

5f7d27b9b3ddee33f85f0f0d8df03540d9cdd48b

I suspect the issue may be that I am passing the 'key' as ASCII instead of HEX. After many hours of research I haven't been able to figure out the necessary changes to make it work. Any help is greatly appreciated.

momo78
  • 23
  • 2

1 Answers1

3

The difference is in how the keys are being converted to "bytes."

The JavaScript snippet is parsing the String as "HEX", which should result in:

[ 0x35, 0x35, ..., 0x36, ... ]

While the C# snippet is just grabbing the ASCII values of each Char in the String, resulting in:

{ 0x33, 0x35, 0x33, 0x35, ..., 0x33, 0x36, ... }
// "3" => U+0033
// "5" => U+0035
// "6" => U+0036

To match, the C# version will need to parse the String as hex as well. One way of doing that is with StringToByteArray(), as defined in another SO post:

// ...
byte[] keyByte = StringToByteArray(key);
// ...
60c9059c9be9bcd092e00eb7f03492fa3259f459
Community
  • 1
  • 1
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199