我需要在C#中转换以下php代码:
<code>$res = mac256($ent, $key); $result = encodeBase64($res); </code>
哪里
<code>function encodeBase64($data)
{
$data = base64_encode($data);
return $data;
}
</code>
和
<code>function mac256($ent,$key)
{
$res = hash_hmac('sha256', $ent, $key, true);//(PHP 5 >= 5.1.2)
return $res;
}
</code>
我使用以下C#代码:
<code>byte[] res = HashHMAC(ent, key); string result = System.Convert.ToBase64String(res); </code>
哪里
<code>public byte[] HashHMAC(string ent, byte[] key)
{
byte[] toEncryptArray =System.Text.Encoding.GetEncoding(28591).GetBytes(ent);
HMACSHA256 hash = new HMACSHA256(key);
return hash.ComputeHash(toEncryptArray);
}
</code>
这个link提供完整的php源代码
我也查看了这篇文章hmac_sha256 in php and c# differ
而这一个C# equivalent to hash_hmac in PHP
但结果却不尽相同.
解决方法:
这段代码可以解决这个问题:
<code>static byte[] hmacSHA256(String data, String key)
{
using (HMACSHA256 hmac = new HMACSHA256(Encoding.ASCII.GetBytes(key)))
{
return hmac.ComputeHash(Encoding.ASCII.GetBytes(data));
}
}
</code>
如果我调用此代码:
<code>Console.WriteLine(BitConverter.ToString(hmacSHA256("1234", "1234")).Replace("-", "").ToLower());
</code>
它返回:
<code>4e4feaea959d426155a480dc07ef92f4754ee93edbe56d993d74f131497e66fb </code>
当我在PHP中运行它时:
<code>echo hash_hmac('sha256', "1234", "1234", false);
</code>
它回来了
<code>4e4feaea959d426155a480dc07ef92f4754ee93edbe56d993d74f131497e66fb </code>
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!