c#和php中的哈希值不同


Not the same hash value in c# and php

我有一个用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#one 的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));
}