2016-11-16 97 views
0

我試圖將一個C#應用程序移植到節點中。 應用程序有這個C#函數生成一個SHA256C#中的HMAC 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#的結果?

回答

2

您的密鑰與C#版本不同。嘗試將十六進制字符串轉換爲原始字節。這種方式加密知道採取字節,而不是實際的字符串。

例如:

var crypto = require('crypto'); 

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