我在C#中有以下的函数,是一个哈希函数,我需要将其转换为PHP。我尝试了一些PHP代码,但结果不同(我并不擅长.NET)。
请注意 hash_hmac 的第四个参数 - 现在设置为 true 以输出原始的二进制数据。
private static string GetSignature(string args, string privatekey)
{
var encoding = new System.Text.ASCIIEncoding();
byte[] key = encoding.GetBytes(privatekey);
var myhmacsha256 = new HMACSHA256(key);
byte[] hashValue = myhmacsha256.ComputeHash(encoding.GetBytes(args));
string hmac64 = Convert.ToBase64String(hashValue);
myhmacsha256.Clear();
return hmac64;
}
在 PHP 中,一个错误的尝试是这样的:
function encode($data,$key)
{
return base64_encode( hash_hmac('sha256', $data, $key ) );
}
答案
DampeS8N下面提供的略有变化的方法对我起了很大作用。
function encode($data,$key)
{
iconv_set_encoding("input_encoding", "ASCII");
iconv_set_encoding("internal_encoding", "ASCII");
iconv_set_encoding("output_encoding", "ASCII");
return base64_encode( hash_hmac('sha256', $data, $key, true ) );
}
请注意 hash_hmac 的第四个参数 - 现在设置为 true 以输出原始的二进制数据。