C# 尝试在C上复制JavaScript哈希#
我试图在C#上复制JavaScript哈希,但得到的结果不同。 JavaScript上的代码是:C# 尝试在C上复制JavaScript哈希#,c#,javascript,hash,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
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
5f7d27b9b3ddee33f85f0f0d8df03540d9cdd48b
我正在尝试的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);
}
它返回以下哈希值:
60c9059c9be9bcd092e00eb7f03492fa3259f459
5f7d27b9b3ddee33f85f0f0d8df03540d9cdd48b
我怀疑问题可能是我将“键”作为ASCII而不是十六进制传递。经过几个小时的研究,我还没能想出必要的改变,使它的工作。非常感谢您的帮助。区别在于
键
如何转换为“字节”
JavaScript代码段正在将字符串
解析为“HEX”
,这将导致:
[ 0x35, 0x35, ..., 0x36, ... ]
而C#snippet只是获取字符串
中每个字符
的ASCII值,导致:
{ 0x33, 0x35, 0x33, 0x35, ..., 0x33, 0x36, ... }
// "3" => U+0033
// "5" => U+0035
// "6" => U+0036
为了匹配,C版本还需要解析字符串
。一种方法是:
为什么你想让不同的散列函数返回相同的东西?@Magus不同的api,但是相同的函数:HMAC-SHA1。我很确定他回答了问题中的问题。不同的输入不应该给出相同的输出。。。