使用.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);
这是我的PHP代码:
hash_hmac( "sha256", utf8_encode( $filename ), utf8_encode( $password ) );
Run Code Online (Sandbox Code Playgroud)
这是我的C#代码:
var hmacsha256 = new HMACSHA256( Encoding.UTF8.GetBytes( password ) );
hmacsha256.ComputeHash( Encoding.UTF8.GetBytes( filename ) );
Run Code Online (Sandbox Code Playgroud)
不幸的是,两个结果都不同 任何人都可以给我一个提示吗?
我需要使用SHA256哈希函数来计算HMAC.我有一个以base64格式编码的密钥.还有一个正确计算HMAC(已验证)的在线工具. http://www.freeformatter.com/hmac-generator.html 我写了以下代码片段:
var signatureHashHexExpected = "559bd871bfd21ab76ad44513ed5d65774f9954d3232ab68dab1806163f806447";
var signature = "123456:some-string:2016-04-12T12:44:16Z";
var key = "AgQGCAoMDhASFAIEBggKDA4QEhQCBAYICgwOEBIUAgQ=";
var shaKeyBytes = Convert.FromBase64String(key);
using (var shaAlgorithm = new System.Security.Cryptography.HMACSHA256(shaKeyBytes))
{
var signatureBytes = System.Text.Encoding.UTF8.GetBytes(signature);
var signatureHashBytes = shaAlgorithm.ComputeHash(signatureBytes);
var signatureHashHex = string.Concat(Array.ConvertAll(signatureHashBytes, b => b.ToString("X2"))).ToLower();
System.Diagnostics.Debug.Assert(signatureHashHex == signatureHashHexExpected);
}
Run Code Online (Sandbox Code Playgroud)
问题:我的代码没有生成正确的HMAC.我通过使用不同的在线工具和替代C#实现验证了不同的步骤.仅确认无法从base64进行转换.我错过了什么?
更新:我的代码计算的signatureHashHex是"a40e0477a02de1d134a5c55e4befa55d6fca8e29e0aa0a0d8acf7a4370208efc"
答案:该问题是由一个误导性的文档引起的,该文件说明密钥是以Base64格式提供的.看到接受的答案:
var shaKeyBytes = System.Text.Encoding.UTF8.GetBytes(key);
Run Code Online (Sandbox Code Playgroud)