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.

3
  • Why do you want different hashing functions to return the same thing? Commented Feb 14, 2014 at 19:21
  • @Magus Different APIs, but same function: HMAC-SHA1. Commented Feb 14, 2014 at 19:22
  • I'm pretty sure he answered the question in the question. Different inputs shouldn't give the same output... Commented Feb 14, 2014 at 19:26

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.