user989818
user989818

Reputation:

md5 hash confusion

My company uses the following algorithm to hash passwords before store it in the database:

    public static string Hash(string value)
    {
        byte[] valueBytes = new byte[value.Length * 2];

        Encoder encoder = Encoding.Unicode.GetEncoder();
        encoder.GetBytes(value.ToCharArray(), 0, value.Length, valueBytes, 0, true);

        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] hashBytes = md5.ComputeHash(valueBytes);

        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < hashBytes.Length; i++)
        {
            stringBuilder.Append(hashBytes[i].ToString("x2"));
        }

        return stringBuilder.ToString();
    }

To me it sounds like a trivial md5 hash, but when I tried to match a password (123456) the algorithm gives me ce0bfd15059b68d67688884d7a3d3e8c, and when I use a standard md5 hash it gives me e10adc3949ba59abbe56e057f20f883e.

A iOS version of the site is being build, and the users needs to login, the password will be hashed before sent. I told the iOS team to use a standard md5 hash, but of course it don't worked out.

I can't unhash the password and hash it again using the standard md5 (of course), and I don't know what exactly tell to the iOS team, in order to get the same hash.

Any help?

Upvotes: 2

Views: 791

Answers (2)

Schiavini
Schiavini

Reputation: 2939

You need to use UTF8 instead of Unicode. The following code works exactly like the PHP md5() function:

    public static string md5(string value)
    {
        byte[] encoded = ASCIIEncoding.UTF8.GetBytes(value);

        MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();
        byte[] hashCode = md5Provider.ComputeHash(encoded);

        string ret = "";
        foreach (byte a in hashCode)
            ret += String.Format("{0:x2}", a);
        return ret;
    }

Upvotes: 2

SLaks
SLaks

Reputation: 888047

You need to use the same encoding on both ends (probably UTF8).

If you replace your code with

byte[] hashBytes = md5.ComputeHash(Encoding.UTF8.GetBytes("123456"));

, you'll get e10adc3949ba59abbe56e057f20f883e.

Upvotes: 7

Related Questions