PHP和C#HMAC SHA256 [英] PHP and C# HMAC SHA256

查看:102
本文介绍了PHP和C#HMAC SHA256的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在C#中转换以下php代码:

I need to convert the following php code in C#:

$res = mac256($ent, $key);
$result = encodeBase64($res);

其中

function encodeBase64($data)
{
    $data = base64_encode($data);
    return $data;
}

function mac256($ent,$key)
{
    $res = hash_hmac('sha256', $ent, $key, true);//(PHP 5 >= 5.1.2)
    return $res;
}

我使用以下C#代码:

byte[] res = HashHMAC(ent, key);
string result = System.Convert.ToBase64String(res);

其中

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);
}

可在以下链接

我还检查了这篇帖子 hmac_sha256在php和c#中的区别

和这一个与PHP中的hash_hmac等效的C#

但是结果不一样.

推荐答案

此代码应能解决问题:

static byte[] hmacSHA256(String data, String key)
{
    using (HMACSHA256 hmac = new HMACSHA256(Encoding.ASCII.GetBytes(key)))
    {
        return hmac.ComputeHash(Encoding.ASCII.GetBytes(data));
    }
}

如果我调用此代码:

Console.WriteLine(BitConverter.ToString(hmacSHA256("1234", "1234")).Replace("-", "").ToLower());

它返回:

4e4feaea959d426155a480dc07ef92f4754ee93edbe56d993d74f131497e66fb

当我在PHP中运行此代码时:

When I run this in PHP:

echo hash_hmac('sha256', "1234", "1234", false);

返回

4e4feaea959d426155a480dc07ef92f4754ee93edbe56d993d74f131497e66fb

这篇关于PHP和C#HMAC SHA256的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆