gpt4 book ai didi

c# - c# 和 php 中的哈希值不一样

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

我有一个用 C# 开发的 Web 服务。它使用 MD5 生成 session key 。

c#:

public static string GetMD5(string pTxt)
{
string sCTxt = "";
byte[] aTxt;
UnicodeEncoding oEnc = new UnicodeEncoding();
aTxt = oEnc.GetBytes(pTxt);
HashAlgorithm oHash = new MD5CryptoServiceProvider();
byte[] aCTxt = oHash.ComputeHash(aTxt);
foreach (byte b in aCTxt)
sCTxt += String.Format("{0:X2}", b);
return (sCTxt);
}

出于多种原因,我必须在 PHP 中创建相同的 GetMD5 方法。当然,基本的 md5() 函数不会返回相同的哈希值(因为 UNICODE)

我尝试用 PHP 模拟代码但没有成功

php:

public function HexToBytes($s) {
return join('', array_map('chr', array_map('hexdec', str_split($s, 2))));
}

public function GetMD5($pStr) {
$data = mb_convert_encoding($pStr, 'UTF-16LE', 'ASCII');
$h = $this->HexToBytes(hash_hmac('md5', $data, ''));
return (base64_encode($h));
}

知道为什么结果不一样吗?

提前致谢


**

已修复!谢谢!

**

有兴趣的可以看看c#的PHP方法

public function str2hex($string) {
$hex = "";
for ($i = 0; $i < strlen($string); $i++)
$hex .= (strlen(dechex(ord($string[$i]))) < 2) ? "0" . dechex(ord($string[$i])) : dechex(ord($string[$i]));
return $hex;
}

public function GetMD5($pStr) {
$data = mb_convert_encoding($pStr, 'UTF-16LE', 'UTF-8');
$h = $this->str2hex(md5($data, true));
return strtoupper($h);
}

最佳答案

我认为您的方法过于复杂了。以下替代方案对我有用:

C# :

public static string GetMD5(string text)
{
byte[] textBytes = Encoding.UTF8.GetBytes(text);
byte[] hash = MD5.Create().ComputeHash(textBytes);

return Convert.ToBase64String(hash);
}

PHP :

public function GetMD5($pStr) {
return base64_encode(
md5(mb_convert_encoding($pStr, "UTF8", "Unicode"), true));
}

关于c# - c# 和 php 中的哈希值不一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9605343/

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