试图在C#上复制JavaScript哈希

时间:2014-02-14 19:14:54

标签: c# javascript hash

我正在尝试在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

我怀疑问题可能是我将'key'作为ASCII而不是HEX传递。经过数小时的研究,我无法找出必要的改变以使其发挥作用。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:3)

区别在于key s如何转换为“ bytes 。”

JavaScript代码段正在将String解析为"HEX",这应该会导致:

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

虽然C#代码段只是抓取Char中每个String的ASCII值,但结果是:

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

要匹配,C#版本还需要将String解析为十六进制。一种方法是使用StringToByteArray(), as defined in another SO post

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