我正在尝试使用API,为此我必须使用SHA384创建签名。文档描述了:
signature = hex(HMAC_SHA384(base64(payload), key=api_secret))
他们举了一个例子:
~$ base64 << EOF
> {
> "request": "/v1/order/status",
> "nonce": 123456,
>
> "order_id": 18834
> }
> EOF
ewogICAgInJlcXVlc3QiOiAiL3YxL29yZGVyL3N0YXR1cyIsCiAgICAibm9uY2UiOiAxMjM0NTYs
CgogICAgIm9yZGVyX2lkIjogMTg4MzQKfQo=
In this example, the api_secret is 1234abcd
echo -n 'ewogICAgInJlcXVlc3QiOiAiL3YxL29yZGVyL3N0YXR1cyIsCiAgICAibm9uY2UiOiAxMjM0NTYsCgogICAgIm9yZGVyX2lkIjogMTg4MzQKfQo=' | openssl sha384 -hmac "1234abcd"
(stdin)= 337cc8b4ea692cfe65b4a85fcc9f042b2e3f702ac956fd098d600ab15705775017beae402be773ceee10719ff70d710f
花了一点时间,但我意识到为了复制原始字符串的base64,我不得不用“\ n”替换“\ r \ n”。
这就是我所拥有的(忽略了我浪费了20分钟努力做好的格式化):
var raw = @"{
""request"": ""/v1/order/status"",
""nonce"": 123456,
""order_id"": 18834
}
";
var data = raw.Replace("\r\n", "\n");
Console.WriteLine(data);
var data64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(data.ToCharArray()));
if (data64 != "ewogICAgInJlcXVlc3QiOiAiL3YxL29yZGVyL3N0YXR1cyIsCiAgICAibm9uY2UiOiAxMjM0NTYsCgogICAgIm9yZGVyX2lkIjogMTg4MzQKfQo=")
{
Console.WriteLine("base64's don't match");
}
Console.WriteLine("ewogICAgInJlcXVlc3QiOiAiL3YxL29yZGVyL3N0YXR1cyIsCiAgICAibm9uY2UiOiAxMjM0NTYsCgogICAgIm9yZGVyX2lkIjogMTg4MzQKfQo=");
Console.WriteLine(data64);
var key = Encoding.UTF8.GetBytes("1234abcd");
using (var hash = new HMACSHA384(key))
{
var hash64 = Convert.ToBase64String(hash.ComputeHash(Encoding.UTF8.GetBytes(data64)));
StringBuilder sb = new StringBuilder();
foreach (char c in hash64)
{
sb.Append(Convert.ToInt32(c).ToString("x"));
}
Console.WriteLine(sb.ToString());
// yields:
// 4d337a49744f70704c50356c744b68667a4a38454b79342f6343724a5676304a6a57414b7356634664314158767135414b2b647a7a753451635a2f3344584550
// should be:
// 337cc8b4ea692cfe65b4a85fcc9f042b2e3f702ac956fd098d600ab15705775017beae402be773ceee10719ff70d710f
}
我的代码输出与文档的预期输出不匹配。有人能看出我做错了吗?
答案 0 :(得分:1)
由于某种原因,您将哈希值转换为base-64字符串,然后将该字符串的每个字符转换为int并转换为十六进制。所有这些都不需要,也没有在“文档”中描述。相反,这样做:
var hashBin = hash.ComputeHash(Encoding.UTF8.GetBytes(data64));
var hashHex = BitConverter.ToString(hashBin).Replace("-", "").ToLowerInvariant();
Console.WriteLine(hashHex);