PHP and C# HMAC SHA256

前端 未结 3 932
既然无缘
既然无缘 2020-12-20 04:30

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

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

where

function enc         


        
3条回答
  •  梦毁少年i
    2020-12-20 05:01

    This code should do the trick:

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

    If I call this code:

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

    It returns:

    4e4feaea959d426155a480dc07ef92f4754ee93edbe56d993d74f131497e66fb
    

    When I run this in PHP:

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

    It returns

    4e4feaea959d426155a480dc07ef92f4754ee93edbe56d993d74f131497e66fb
    

提交回复
热议问题