gpt4 book ai didi

c# - C#'s HMAC SHA512 value too short compared to Salesforce' 秒?

转载 作者:行者123 更新时间:2023-12-04 04:09:46 27 4
gpt4 key购买 nike

为什么我从 Salesforce 的 Apex 和 C# 得到不同的 mac 值?

我有以下 C# 代码来生成签名:

using (var hmacSha512 = System.Security.Cryptography.HMACSHA512.Create())
{
byte[] payload = System.Text.Encoding.UTF8.GetBytes("payload");
hmacSha512.Key = System.Text.Encoding.UTF8.GetBytes("key");
byte[] macBytes = hmacSha512.ComputeHash(payload);
string mac = BitConverter.ToString(macBytes).Replace("-", string.Empty).ToLower();
Console.WriteLine(mac);
}

我已经尝试在 Apex 中实现相应的代码:
Blob payload = Blob.valueOf('payload');
Blob key = Blob.valueOf('key');
Blob macBlob = Crypto.generateMac('hmacSHA512', payload, key);
string mac = EncodingUtil.convertToHex(macBlob);
System.debug(mac);

但我得到的结果是不同的:
C#:    2f3902cd1626fa7fdfb67e93109f50412ad71531
Apex: 185beceee65a5ed7e43f7cc98530bfab1b0d00679488a47225255d04594fd7f17ed6908e7a08df57ac14c9e56c2fdef83ee9adaf9df2ff9f61465898c5d78c00

如您所见,Apex 结果明显长于 C# 等效结果。自然地,我决定检查 Blob->Hex 是否按我预期的那样工作,同时以十六进制打印有效载荷和键值:
// C#:
Console.WriteLine(BitConverter.ToString(payload).Replace("-", string.Empty).ToLower());
Console.WriteLine(BitConverter.ToString(hmacSha512.Key).Replace("-", string.Empty).ToLower());

// Results:
// 7061796c6f6164
// 6b6579

// Apex:
System.debug(EncodingUtil.convertToHex(payload));
System.debug(EncodingUtil.convertToHex(key));

// Results:
// 7061796c6f6164
// 6b6579

所以 blob 值是我所期望的,并且转换为十六进制的工作(不出所料)正如我所期望的。

如果我在 this online service 上尝试相同的有效负载和组合键,我得到与 Salesforce 相同的值(value)。甚至 Java 也与 Salesforce 相同。这让我认为 C# 实现是不正确的,但我不明白为什么。

我想也许我需要手动散列 SHA512 并将其传递给 HMCSHA512,但这对长度没有影响。

我在 C# 实现中做错了什么?

最佳答案

看来我其实是想用KeyedHashAlgorithm使用“HmacSHA512”:

using (var hmacSha512 = System.Security.Cryptography.KeyedHashAlgorithm.Create("HmacSHA512"))

我意识到这在 .NET Core 中不起作用(它在运行 Create 方法时抛出异常),因此我将其更改为:
using (var hmacSha512 = new System.Security.Cryptography.HMACSHA512())

我不确定为什么这会提供不同的结果,但是当我运行它时,我得到与 Apex 相同的结果:
185beceee65a5ed7e43f7cc98530bfab1b0d00679488a47225255d04594fd7f17ed6908e7a08df57ac14c9e56c2fdef83ee9adaf9df2ff9f61465898c5d78c00

关于c# - C#'s HMAC SHA512 value too short compared to Salesforce' 秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61947247/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com