【发布时间】:2012-03-07 16:26:01
【问题描述】:
我有一个用 c# 开发的 Web 服务。 它使用 MD5 生成会话密钥。
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# 版本是十六进制编码结果,而 php 版本是 base64 编码结果。这肯定会产生不同的结果。
-
加上 PHP 代码正在执行 HMAC 而不是直接哈希。