c# - 将 C# 哈希函数转换为 PHP

标签 c# php hmac

我在 C# 中有以下函数,我需要将其转换为 PHP 的散列函数。我在 PHP 中尝试了一些东西,但没有得到相同的结果(我对 .NET 一点也不擅长)

private static string GetSignature(string args, string privatekey)
{
    var encoding = new System.Text.ASCIIEncoding();
    byte[] key = encoding.GetBytes(privatekey);
    var myhmacsha256 = new HMACSHA256(key);
    byte[] hashValue = myhmacsha256.ComputeHash(encoding.GetBytes(args));
    string hmac64 = Convert.ToBase64String(hashValue);
    myhmacsha256.Clear();
    return hmac64;
} 

PHP 中的一个(错误的)尝试是这样的:

function encode($data,$key)
{
    return base64_encode( hash_hmac('sha256', $data, $key ) );
}

答案

DampeS8N 下面建议的内容略有不同,对我有用。

function encode($data,$key)
{
    iconv_set_encoding("input_encoding", "ASCII");
    iconv_set_encoding("internal_encoding", "ASCII");
    iconv_set_encoding("output_encoding", "ASCII");

    return base64_encode( hash_hmac('sha256', $data, $key, true ) );
}

也请不要将 hash_hmac 的第四个参数设置为 true 以将原始输出作为二进制数据

最佳答案

我怀疑您的 .net 代码的第一行是罪魁祸首。 PHP has no encoding for the string本身,因此当需要散列时,它要么散列内部 PHP 字符串格式的字节(不太可能,其他人可以确认吗?),要么很可能首先转换为其他内容。在这种情况下,可能是 unicode,它与 .net 请求的字符串在 ASCII 中的字节绝对不同。

我的建议是确保 PHP 也使用 ASCII,with iconv , 以实现互操作性。

function encode($data,$key)
{
    return base64_encode( hash_hmac('sha256', iconv( iconv_get_encoding( "internal_encoding"), "ASCII", $data ), iconv( iconv_get_encoding( "internal_encoding"), "ASCII", $key ) ) );
}

但是,我不能确定上面的代码是否会输出所需的哈希值,因为我手头没有 .net 来测试初始代码。但这可能会为您指明正确的方向。

如果这不起作用,iconv_get_encoding( 中的值可能是罪魁祸首,尝试使用 "output_encoding""input_encoding" 作为好吧。您也可能需要使用 iconv_set_encoding(.

将这些相同的值设置为 ASCII

祝你好运!


更新!这是最终起作用的:

function encode($data,$key)
{
    iconv_set_encoding("input_encoding", "ASCII");
    iconv_set_encoding("internal_encoding", "ASCII");
    iconv_set_encoding("output_encoding", "ASCII");

    return base64_encode( hash_hmac('sha256', $data, $key, true ) );
}

关于c# - 将 C# 哈希函数转换为 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8786802/

相关文章:

c# - iTextSharp PdfTextExtractor GetTextFromPage 抛出 NullReferenceException

php - 如何避免 file_get_contents 错误 : "Couldn' t resolve host name"

php - Google Drive API 访问 token 和重定向网址问题

php - 如何创建完整的 Laravel rest api 并与 Laravel REST Controller 混淆

encryption - 为什么我的 crypto.createHmac() 会为相同的输入生成不同的 HMAC?

authentication - hMAC 认证中的时间戳

javascript - 将加密 hmac 转换为 crypto-js hmac 字符串

c# - 将网格添加到 ItemsControl 的 ItemsPanelTemplate

c# - 数据库更新异常 : Which field is causing "String or binary data would be truncated"

c# - 创建线程时出现 NullReferenceException