正在尝试在C#上复制JavaScript哈希



我试图在C#上复制一个JavaScript哈希,但我得到了不同的结果。JavaScript上的代码是:

var key = "35353535353535366363636363",
credentials = "web:web",  
shaObj = new jsSHA(credentials, "ASCII"), 
hash = shaObj.getHMAC(key, "HEX", "SHA-1", "HEX"); // key and generated hash are hex values
alert("Hash: " + hash);

它返回以下散列:

60c9059c9be9bcd092e00eb7f03492fa3259f459

我正在尝试的C#代码是:

key = "35353535353535366363636363";
string credentials = "web:web";
var encodingCred = new System.Text.ASCIIEncoding();
var encodingKey = new System.Text.ASCIIEncoding();
byte[] keyByte = encodingKey.GetBytes(key);
byte[] credentialsBytes = encodingCred.GetBytes(credentials);
using (var hmacsha1 = new HMACSHA1(keyByte))
{
byte[] hashmessage = hmacsha1.ComputeHash(credentialsBytes);
string hash = BitConverter.ToString(hashmessage).Replace("-", string.Empty).ToLower();
Console.WriteLine("HASH: " + hash);              
} 

它返回以下散列:

5f7d27b9b3ddee33f85f0f0d8df03540d9cdd48b

我怀疑问题可能是我将"密钥"作为ASCII而不是HEX传递。经过几个小时的研究,我还没能想出必要的改变来让它发挥作用。非常感谢您的帮助。

区别在于keys如何转换为">字节">

JavaScript片段正在将String解析为"HEX",这将导致:

[ 0x35, 0x35, ..., 0x36, ... ]

而C#代码段只是获取String中每个Char的ASCII值,结果是:

{ 0x33, 0x35, 0x33, 0x35, ..., 0x33, 0x36, ... }
// "3" => U+0033
// "5" => U+0035
// "6" => U+0036

为了匹配,C#版本还需要将String解析为十六进制。一种方法是使用StringToByteArray(),正如另一篇SO文章中所定义的那样

// ...
byte[] keyByte = StringToByteArray(key);
// ...
60c9059c9be9bcd092e00eb7f03492fa3259f459

最新更新