0

I'm want to use a REST API which requires a signature, which is a hash of the message using a secret key. I have a JavaScript implementation of it which works, but when I try to do the same thing in C#, it produces a different result which, according to the API response, does not seem to be correct.

The JavaScript code that produces the desired signature:

let signature = crypto.createHmac('sha256', secret_key).update(message).digest('hex');

The C# code that does not produce the same desired signature:

var hash = new HMACSHA256(key);
byte[] signature = hash.ComputeHash(message);
StringBuilder hexDigest = new StringBuilder();
foreach (byte b in signature)
     hexDigest.Append(String.Format("{0:x2}", b).ToUpper());

Would appreciate if someone can tell me what I need to change in the C# code to reproduce the same result.

Batash
  • 101
  • 2
  • 12

1 Answers1

2

I don't know what to change in the code you provided. But let me guide you.

You probably have different keys or messages because of text encoding. For example, with Javascript I've tried the following code:

const secret_key = 'abcdefg';
const message = 'Hello, World!';
let signature = crypto.createHmac('sha256', secret_key).update(message).digest('hex');

The signature is 37c559140f3c04743337019ef0f693ee8a469c9d41a925b8f3b624796dce0ba0.

In C# I used the UTF8 encoding and got the same result.

var key = Encoding.UTF8.GetBytes("abcdefg");
var hash = new HMACSHA256(key);
var message = Encoding.UTF8.GetBytes("Hello, World!");
byte[] signature = hash.ComputeHash(message);
    StringBuilder hexDigest = new StringBuilder();
    foreach (byte b in signature)
         hexDigest.Append(String.Format("{0:x2}", b));

If I used Encoding.Unicode, I would get different signature eb2b452cf518dc647a5014b7dd46da2e7bd2300aae394ea9cbb4eba492c093f5.

qwermike
  • 1,446
  • 2
  • 12
  • 24
  • Thanks for pointing that out, it actually made me reconsider the values of the inputs. The thing is, the message has to be a base64 encoded json and when I compared the messages, it seemed to be the same, but in reality as i checked now, they werent completely the same strings, which was not easily noticable by looking at it. I had one json attribute in a different order. I was too convinced that something is wrong with the hashing, since it has multiple steps. – Batash Jan 13 '19 at 17:35