我需要在.NET和C#中使用HMAC SHA512生成一个完整性字符串,并将其提供给PHP服务器。
Encoding encoding = Encoding.UTF8;
byte[] keyByte = encoding.GetBytes(key);
HMACSHA512 hmacsha512 = new HMACSHA512(keyByte);
byte[] messageBytes = encoding.GetBytes(message);
byte[] hashmessage = hmacsha512.ComputeHash(messageBytes);
return(ByteToString(hashmessage).toUpper());
但它与 PHP 的 hash_hmac() 不匹配
$hmac = strtoupper(hash_hmac($pbx_hash, $msg, $binKey));
我尝试在C#中更改编码(UTF8,ASCII,Unicode),但没有成功。
我尝试了许多在网上找到的解决方案,但没有一个能给出相同的字符串 :(
我无法更改PHP代码,并且不知道C#中哪里出了问题。
编辑 这是ByteToString
(从评论中复制):
static string ByteToString(byte[] buff)
{
string sbinary = "";
for (int i = 0; i < buff.Length; i++)
{
sbinary += buff[i].ToString("X2"); /* hex format */
}
return (sbinary);
}
在经过多次尝试后,我发现如果PHP hash_hmac的密钥是字符串而不是字节数组,则会得到相同的结果。似乎问题出在PHP转换函数$binKey = pack("H*", $keyTest)上。
ByteToString
? - cuongle