Batash
Batash

Reputation: 111

Creating a hash of a message in C#

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.

Upvotes: 0

Views: 1380

Answers (1)

qwermike
qwermike

Reputation: 1496

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.

Upvotes: 2

Related Questions