我尝试在 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 而不是十六进制传递。经过几个小时的研究,我无法找出使其发挥作用所需的更改。非常感谢任何帮助。
最佳答案
区别在于 key
如何转换为“字节”。
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()
, as defined in another SO post :
// ...
byte[] keyByte = StringToByteArray(key);
// ...
60c9059c9be9bcd092e00eb7f03492fa3259f459
关于c# - 尝试在 C# 上复制 JavaScript 哈希值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21787697/