.net与php加密方法等效转换:hmacsha256和md5
本文阐述如何将C# (.NET)的HMACSHA256加密方法等效转换为PHP代码,并确保加密结果一致。 原始C#代码如下:
public static string hmacsha256(string encrypttext, string encryptkey){ using var mac = new HMACSHA256(Encoding.UTF8.GetBytes(encryptkey)); var hash = mac.ComputeHash(Encoding.UTF8.GetBytes(encrypttext)); var txt = Encoding.UTF8.GetBytes(encrypttext); var all = new byte[hash.Length + txt.Length]; Array.Copy(hash, 0, all ,0 , hash.Length); Array.Copy(txt, 0, all ,hash.Length, txt.Length); using var md5 = MD5.Create(); return Convert.ToBase64String(md5.ComputeHash(all)); }
此代码使用HMACSHA256算法对输入文本encrypttext使用密钥encryptkey进行签名,然后将签名结果与原文拼接,再使用MD5算法进行二次哈希,最后Base64编码返回结果。
对应的PHP代码如下:
<?php function hmacsha256_php($encrypttext, $encryptkey) { $encrypted = hash_hmac('sha256', $encrypttext, $encryptkey, true); $combined = $encrypted . $encrypttext; return base64_encode(md5($combined, true)); } $data = 'hello'; $secret = 'world'; $phpResult = hmacsha256_php($data, $secret); echo "PHP加密结果: " . $phpResult . "\n"; ?>
此PHP代码利用PHP内置的哈希函数实现相同功能。hash_hmac('sha256', $encrypttext, $encryptkey, true)计算HMACSHA256哈希值,true参数确保返回原始二进制数据。 然后将哈希值与原始数据拼接,使用md5($combined, true)进行MD5哈希(true同样返回二进制数据),最后base64_encode()进行Base64编码。 这与C#代码逻辑完全对应,保证加密结果一致性。
立即学习“PHP免费学习笔记(深入)”;
以上就是.NET和PHP加密方法如何实现HMACSHA256和MD5的等效转换?的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号