将 C# 中的密码学与 NodeJS 相匹配——创建 Hash SHA256

Matching cryptography in C# to NodeJS - create Hash SHA256

我正在尝试将一些 C# 加密代码移植到 NodeJS 环境中。

可以在此处查看示例 C# 代码: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);
    }

在 NodeJS 中,我使用 'crypto' 库来完成相同的任务。

/// 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());

如果我检查两者的注销信息,我可以看到密钥匹配,缓冲区值为:

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

但是返回的散列值不匹配。我一定是在 NodeJS 的哈希端做错了什么,但是发送了相同的值来创建哈希?

而不是

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

你必须使用

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

here

那么你会得到相同的结果。