节点中的C#HMAC Sha256等效值

节点中的C#HMAC Sha256等效值,c#,node.js,sha256,hmac,C#,Node.js,Sha256,Hmac,我正在尝试将一个C#应用程序移植到节点中。 该应用程序具有生成Sha256的C#函数 public static string CreateSHA256Signature(string targetText) { string _secureSecret = "E49756B4C8FAB4E48222A3E7F3B97CC3"; byte[] convertedHash = new byte[_secureSecret.Le

我正在尝试将一个C#应用程序移植到节点中。 该应用程序具有生成Sha256的C#函数

    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

如何在节点中获得相同的C#结果?

您的密钥与C#版本不同。尝试将十六进制字符串转换为原始字节。这样,crypto知道采用字节而不是实际字符串

例如:

var crypto = require('crypto');

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

import hmac
import hashlib
import binascii

def create_sha256_signature(key, message):
    byte_key = binascii.unhexlify(key)
    message = message.encode()
    return hmac.new(byte_key, message, hashlib.sha256).hexdigest().upper()
    

他要求的是Node.js,而不是Python
import hmac
import hashlib
import binascii

def create_sha256_signature(key, message):
    byte_key = binascii.unhexlify(key)
    message = message.encode()
    return hmac.new(byte_key, message, hashlib.sha256).hexdigest().upper()