gpt4 book ai didi

c# - PHP 和 C# HMAC SHA256

转载 作者:行者123 更新时间:2023-11-30 19:15:46 24 4
gpt4 key购买 nike

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

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

完整的 php 源代码可在此 link 获得

我也查看了这篇文章hmac_sha256 in php and c# differ

还有这个C# equivalent to hash_hmac in PHP

但结果不一样。

最佳答案

这段代码应该可以解决问题:

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 中运行它时:

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

返回

4e4feaea959d426155a480dc07ef92f4754ee93edbe56d993d74f131497e66fb

关于c# - PHP 和 C# HMAC SHA256,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33419006/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com