1

I am trying to port some C# crypto code over to a NodeJS environment.

The example C# code can be seen here: https://dotnetfiddle.net/t0y8yD

    byte[] key = Convert.FromBase64String("loQj47u9A5Vj6slaKmCShd/wg2hS+Mn5mM2s5NT5GzF3um1WsbFan8y7cxDVEai8ETG5hZ+CqPDrRBJ/V0yRFA==");
    Console.WriteLine(BitConverter.ToString(key));

    byte[] data = System.Text.Encoding.UTF8.GetBytes("9644873");
    byte[] mac = null;

    using (System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(key))
    {
        mac = hmac.ComputeHash(data);
    }

In NodeJS I am using the 'crypto' library to accomplish the same.

/// key === matches above.  
  var buf = Buffer.from(key, "base64");
  console.log("buff");
  console.log(buf);

  var randomId = 9644873;

  var hmac = crypto.createHash("sha256", buf);
  hmac.update(randomId.toString());

  console.log("hash");
  console.log(hmac.digest());

If I check the logged out information for both I can see the key matches, the buffer value of:

96-84-23-E3-BB-BD-03-95-63-EA-C9-5A-2A-60-92-85-DF-F0-83-68-52-F8-C9-F9-98-CD-AC-E4-D4-F9-1B-31-77-BA-6D-56-B1-B1-5A-9F-CC-BB-73-10-D5-11-A8-BC-11-31-B9-85-9F-82-A8-F0-EB-44-12-7F-57-4C-91-14

However the returned hash value does not match. I must be doing something wrong on the hash side in NodeJS but the same values are being sent to create the hash?

StuartM
  • 6,743
  • 18
  • 84
  • 160

1 Answers1

2

Instead of

var hmac = crypto.createHash("sha256", buf);

you have to use

var hmac = crypto.createHmac("sha256", buf);

see here

Then you'll get identical results.

jps
  • 20,041
  • 15
  • 75
  • 79
  • This is the perfect use case for SO. I've been on that page most of the day... Thanks, that works a treat – StuartM Mar 19 '20 at 16:35
  • glad to help :-) – jps Mar 19 '20 at 16:39
  • Not sure if you can help on my follow on question at all, but thought as you'd seen this you might be able to. Thanks - https://stackoverflow.com/questions/60764586/matching-ouput-for-httpserverutility-urltokenencode-in-nodejs-javascript – StuartM Mar 19 '20 at 20:29
  • after racking my brains for 3 days, this simple comment saved my day. Thanks! – cyanotrix Nov 02 '22 at 09:21