1

I have to replicate C# hash from the code below into PHP. I have been searching but didn't find a solution so far.

From this article on creating an md5 hash string:

using System;
using System.Text;
using System.Security.Cryptography;

// Create an md5 sum string of this string
static public string GetMd5Sum(string str)
{
    // First we need to convert the string into bytes, which
    // means using a text encoder.
    Encoder enc = System.Text.Encoding.Unicode.GetEncoder();

    // Create a buffer large enough to hold the string
    byte[] unicodeText = new byte[str.Length * 2];
    enc.GetBytes(str.ToCharArray(), 0, str.Length, unicodeText, 0, true);

    // Now that we have a byte array we can ask the CSP to hash it
    MD5 md5 = new MD5CryptoServiceProvider();
    byte[] result = md5.ComputeHash(unicodeText);

    // Build the final string by converting each byte
    // into hex and appending it to a StringBuilder
    StringBuilder sb = new StringBuilder();
    for (int i=0;i<result.Length;i++)
    {
        sb.Append(result[i].ToString("X2"));
    }

    // And return it
    return sb.ToString();
}

For input = "123", the above code gives me "5FA285E1BEBE0A6623E33AFC04A1FBD5"

I have tried the following PHP code but it does not give the same output.

From the SO question PHP MD5 not matching C# MD5:

$str = "123";
$strUtf32 = mb_convert_encoding($str, "UTF-32LE");
echo md5($strUtf32);

This code has the result = "a0d5c8a4d386f15284ec25fe1eeeb426". By the way, changing UTF-32LE to utf-8 or utf-16 still does not give me the same result.

Can anyone help?

Community
  • 1
  • 1
Rex
  • 11
  • 3

2 Answers2

2

Yep, as CodesInChaos suggests, you got the encodings wrong.

On php side try this:

$str = "123";
$strUtf32 = mb_convert_encoding($str, "UTF-16LE");
echo md5($strUtf32);

This will give you 5FA285E1BEBE0A6623E33AFC04A1FBD5. This will match System.Text.Encoding.Unicode on the c# side.

Otherwise change System.Text.Encoding.Unicode to System.Text.Encoding.UTF32 on the c# side. This will give you A0D5C8A4D386F15284EC25FE1EEEB426.

Andrew Savinykh
  • 25,351
  • 17
  • 103
  • 158
0

Uhh, the C# code creates a MD5 hash and the PHP mb_convert_encoding function just encodes the string...

Plus, this is NOT THE FULL CODE from the link you gave. You are missing the important MD5 function:

$str = "123";
$strUtf32 = mb_convert_encoding($str, "UTF-16");
echo md5($strUtf32); <=====

If that code matches there should be NO REASON why that shouldn't work, as the MD5 algorithm is still the same and does not vary from language to language.

CC Inc
  • 5,842
  • 3
  • 33
  • 64