Rob*_*tea 2 php c# sha256 hmac
我需要在C#中转换以下php代码:
$res = mac256($ent, $key);
$result = encodeBase64($res);
Run Code Online (Sandbox Code Playgroud)
哪里
function encodeBase64($data)
{
$data = base64_encode($data);
return $data;
}
Run Code Online (Sandbox Code Playgroud)
和
function mac256($ent,$key)
{
$res = hash_hmac('sha256', $ent, $key, true);//(PHP 5 >= 5.1.2)
return $res;
}
Run Code Online (Sandbox Code Playgroud)
我使用以下C#代码:
byte[] res = HashHMAC(ent, key);
string result = System.Convert.ToBase64String(res);
Run Code Online (Sandbox Code Playgroud)
哪里
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);
}
Run Code Online (Sandbox Code Playgroud)
这个链接提供完整的php源代码
我也在php中检查了这篇文章hmac_sha256和c#的区别
但结果却不尽相同.
这段代码可以解决这个问题:
static byte[] hmacSHA256(String data, String key)
{
using (HMACSHA256 hmac = new HMACSHA256(Encoding.ASCII.GetBytes(key)))
{
return hmac.ComputeHash(Encoding.ASCII.GetBytes(data));
}
}
Run Code Online (Sandbox Code Playgroud)
如果我调用此代码:
Console.WriteLine(BitConverter.ToString(hmacSHA256("1234", "1234")).Replace("-", "").ToLower());
Run Code Online (Sandbox Code Playgroud)
它返回:
4e4feaea959d426155a480dc07ef92f4754ee93edbe56d993d74f131497e66fb
Run Code Online (Sandbox Code Playgroud)
当我在PHP中运行它时:
echo hash_hmac('sha256', "1234", "1234", false);
Run Code Online (Sandbox Code Playgroud)
它回来了
4e4feaea959d426155a480dc07ef92f4754ee93edbe56d993d74f131497e66fb
Run Code Online (Sandbox Code Playgroud)