将 Javascript HMAC 转换为 C#
Convert Javascript HMAC to C#
hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secret_buffer);
hmac.update(path, secret_buffer);
var Sign= hmac.finalize();
var signature = base64_encode(Sign);
已经用 C# 尝试过,但无法得到相同的答案
var key1 = sha1.ComputeHash(Encoding.UTF8.GetBytes("Test"));
var key2 = key1.Concat(Encoding.UTF8.GetBytes("Test"));
var key3 = sha1.ComputeHash(key2);
var hmac= Convert.ToBase64String(key3);
请给出一些解决方案?
你的JS代码相当于下面的代码(假设你的base64_encode()
方法实现正确):
var secret_buffer = "secret";
var path = "text";
signature = CryptoJS.HmacSHA256(path, secret_buffer).toString(CryptoJS.enc.Base64);
console.log(signature);
在 С# 中,等价物是:
string secret_buffer = "secret";
string path = "text";
using (var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secret_buffer)))
{
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(path));
var signature = Convert.ToBase64String(hash);
Console.WriteLine(signature);
}
hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, secret_buffer);
hmac.update(path, secret_buffer);
var Sign= hmac.finalize();
var signature = base64_encode(Sign);
已经用 C# 尝试过,但无法得到相同的答案
var key1 = sha1.ComputeHash(Encoding.UTF8.GetBytes("Test"));
var key2 = key1.Concat(Encoding.UTF8.GetBytes("Test"));
var key3 = sha1.ComputeHash(key2);
var hmac= Convert.ToBase64String(key3);
请给出一些解决方案?
你的JS代码相当于下面的代码(假设你的base64_encode()
方法实现正确):
var secret_buffer = "secret";
var path = "text";
signature = CryptoJS.HmacSHA256(path, secret_buffer).toString(CryptoJS.enc.Base64);
console.log(signature);
在 С# 中,等价物是:
string secret_buffer = "secret";
string path = "text";
using (var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(secret_buffer)))
{
var hash = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(path));
var signature = Convert.ToBase64String(hash);
Console.WriteLine(signature);
}