title: Not the same hash value in c# and php
body: <p>I have a web service developed in c#. 
  It uses <strong>MD5</strong> to generate session key.</p>
  
  <h2>c# :</h2>
  
  <pre><code>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);
  }
  </code></pre>
  
  <p>For several reasons, I have to make the same GetMD5 method in <strong>PHP</strong>.
  Of course, the basic md5() function does not return the same hash (because of the UNICODE)</p>
  
  <p>I tried to simulate the code in PHP but with no success</p>
  
  <h2>php:</h2>
  
  <pre><code>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-&gt;HexToBytes(hash_hmac('md5', $data, ''));
      return (base64_encode($h));
  }
  </code></pre>
  
  <p>Any idea why the result are not the same ?</p>
  
  <p>Thanks in advance</p>
  
  <hr>
  
  <p>**</p>
  
  <h2>FIXED! Thanks!</h2>
  
  <p>**</p>
  
  <p>For those interested, here is the PHP method that matches the c# one</p>
  
  <pre><code>public function str2hex($string) {
     $hex = "";
     for ($i = 0; $i &lt; strlen($string); $i++)
        $hex .= (strlen(dechex(ord($string[$i]))) &lt; 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-&gt;str2hex(md5($data, true));
     return strtoupper($h);
  }
  </code></pre>