【问题标题】:C# HMAC Sha256 equivalent in NodeNode 中的 C# HMAC Sha256 等效项
【发布时间】:2021-02-22 19:23:37
【问题描述】:

我正在尝试将 C# 应用程序移植到 Node.js 中。 该应用程序具有此 C# 函数来生成 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

我尝试如下使用节点加密:

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

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

【问题讨论】:

    标签: c# node.js sha256 hmac


    【解决方案1】:

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

    例如:

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

    【讨论】:

      【解决方案2】:

      对于 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()
          
      

      http://www.gauravvjn.com/generate-hmac-sha256-signature-in-python/

      【讨论】:

      • 他要求的是 Node.js,而不是 Python
      猜你喜欢
      • 1970-01-01
      • 2020-10-18
      • 1970-01-01
      • 2013-02-09
      • 2016-01-29
      • 1970-01-01
      • 1970-01-01
      • 2017-01-14
      • 2016-08-03
      相关资源
      最近更新 更多