I have a web service developed in c#.
It uses MD5 to generate 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);
}
For several reasons, I have to make the same GetMD5 method in PHP.
Of course, the basic md5() function does not return the same hash (because of the UNICODE)
I tried to simulate the code in PHP but with no success
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));
}
Any idea why the result are not the same ?
Thanks in advance
**
FIXED! Thanks!
**
For those interested, here is the PHP method that matches the c# one
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);
}
I think you just overcomplicated your methods. The following alternatives worked for me:
C#:
PHP: