【发布时间】:2021-08-27 18:42:15
【问题描述】:
我们得到了this C# snippet,它会生成一些用于 Rest API 调用的字符串。
我们必须在 PHP 中实现它。客户端也给我们提供了一个PHP sn-p,但是PHP返回的字符串和C#返回的字符串不同。你能说出什么是错的吗?我需要 PHP sn-p 提供与 C# 相同的输出。
这里的函数我也分享一下,你可能会更容易阅读
C#
public static string CalculateDigest(string publicKey, string privateKey, string message)
{
var digest = "";
var hash = new System.Security.Cryptography.HMACSHA256(System.Text.Encoding.UTF8.GetBytes(privateKey));
var correctHash = string.Join(string.Empty, hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(message)).Select(b => b.ToString("x2")));
digest = publicKey + ":" + correctHash;
return digest;
}
PHP
$digest = $PUBLIC_KEY.":".Hash_hmac("sha256", $message, $PRIVATE_KEY);
【问题讨论】:
-
(注意使用,
string.Concat(...)而不是string.Join(string.Empty, ...))
标签: c# php cryptography sha256 hmac