Ashraf Fayad Ashraf Fayad - 11 months ago 128
Node.js Question

C# HMAC Sha256 equivalent in Node

I'm trying to port a C# application into Node.
The app has this C# function to generate a Sha256

public static string CreateSHA256Signature(string targetText)
string _secureSecret = "E49756B4C8FAB4E48222A3E7F3B97CC3";
byte[] convertedHash = new byte[_secureSecret.Length / 2];
for (int i = 0; i < _secureSecret.Length / 2; i++)
convertedHash[i] = (byte)Int32.Parse(_secureSecret.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);

string hexHash = "";
using (HMACSHA256 hasher = new HMACSHA256(convertedHash))
byte[] hashValue = hasher.ComputeHash(Encoding.UTF8.GetBytes(targetText));
foreach (byte b in hashValue)
hexHash += b.ToString("X2");
return hexHash;
Response.Write(CreateSHA256Signature("TEST STRING"));
// returns 55A891E416F480D5BE52B7985557B24A1028E4DAB79B64D0C5088F948EB3F52E

I tried to use node crypto as following:

console.log(crypto.createHmac('sha256', 'E49756B4C8FAB4E48222A3E7F3B97CC3').update('TEST STRING', 'utf-8').digest('hex'))
// returns bc0a28c3f60d323404bca7dfc4261d1280ce46e887dc991beb2c5bf5e7ec6100

How can I get the same C# result in node?

Answer Source

Your key is different from the C# version. Try to convert the hex string to raw bytes. This way crypto knows to take the bytes instead of the actual string.

For example:

var crypto = require('crypto');

var key = Buffer.from('E49756B4C8FAB4E48222A3E7F3B97CC3', 'hex');
console.log(crypto.createHmac('sha256', key).update('TEST STRING').digest('hex'))