MissCoder87
MissCoder87

Reputation: 2669

c# md5 to be the same as PHPs md5 hash

I'm going a bit crazy with this! I'm trying to authenticate my app against an existing database (so I can't change the PHP side) and I need to convert my password field to be the same as php's md5(moo) command.

However, each formula I try to create the hash comes up with the same md5 has, very different to whats in the database.

Is there a formula that produces the same results?

I've tried:

 public static string MbelcherEncodePassword(string originalPassword)
        {
            Byte[] originalBytes;
            Byte[] encodedBytes;
            MD5 md5;

            // Conver the original password to bytes; then create the hash
            md5 = new MD5CryptoServiceProvider();
            originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
            encodedBytes = md5.ComputeHash(originalBytes);

            // Bytes to string
            return System.Text.RegularExpressions.Regex.Replace(BitConverter.ToString(encodedBytes), "-", "").ToLower();


        }

And:

public static string MD5(string password)
        {
            byte[] textBytes = System.Text.Encoding.Default.GetBytes(password);
            try
            {
                System.Security.Cryptography.MD5CryptoServiceProvider cryptHandler;
                cryptHandler = new System.Security.Cryptography.MD5CryptoServiceProvider();
                byte[] hash = cryptHandler.ComputeHash(textBytes);
                string ret = "";
                foreach (byte a in hash)
                {
                    if (a < 16)
                        ret += "0" + a.ToString("x");
                    else
                        ret += a.ToString("x");
                }
                return ret;
            }
            catch
            {
                throw;
            }
        }

and:

 public static string MD5Hash(string text)
            {
                System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
                return System.Text.RegularExpressions.Regex.Replace(BitConverter.ToString(md5.ComputeHash(ASCIIEncoding.Default.GetBytes(text))), "-", "");
            }

To no avail. Any help really will be appreciated!

Thanks

Upvotes: 0

Views: 607

Answers (1)

loopedcode
loopedcode

Reputation: 4893

Following should give you same hex string as PHP md5:

public string GetMd5Hex(MD5 crypt, string input)
{
    return crypt.ComputeHash(UTF8Encoding.UTF8.GetBytes(input))
        .Select<byte, string>(a => a.ToString("x2"))
        .Aggregate<string>((a, b) => string.Format("{0}{1}", a, b));
}

Upvotes: 1

Related Questions