2

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?

1
  • 1
    That's probably because of the encoding. I will provide you a function that works exactly like php. Commented Mar 20, 2012 at 18:13

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Good point! Thank you, I ll tell then to use unicode instead.
@myself: .Net's Encoding.Unicode means UTF16 Little-Endian.
2

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; } 

1 Comment

I can't change the code, but I tell then to use unicode instead.