小编Phi*_*ppe的帖子

C#相当于PHP中的hash_hmac

使用.NET和C#我需要使用HMAC SHA512为PHP服务器提供完整性字符串.在C#中使用:

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());
Run Code Online (Sandbox Code Playgroud)

但它与PHP hash_hmac()PHP代码不匹配:

$hmac = strtoupper(hash_hmac($pbx_hash, $msg, $binKey));
Run Code Online (Sandbox Code Playgroud)

我尝试用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);
}    
Run Code Online (Sandbox Code Playgroud)

经过多次发布后,我发现如果PHP hash_hmac键是一个字符串,而不是一个字节数组,我会得到相同的结果.似乎问题出在PHP转换函数$ binKey = pack("H*",$ keyTest);

c# hmac sha512

25
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×1

hmac ×1

sha512 ×1