Creating an MD5 hashed password
Ever wondered how the FormsAuthentication.HashPasswordForStoringInConfigFile method works? Me neither, but I had to basically replicate its functionality the other day. I tried decompiling it using Reflector, but it really wasn’t any help.
The part I was struggling with was working out how to get a Hex string from a Base64 string (which is what the ComputeHash method will return to you). Turns out you need to call the ToString() method on each byte, specifying “X2″ as the format. Of course! Well, nothing illustrates a point like some code, so here it is:
/// <summary>
/// Return a Hex-string encoded validation for the nominated password
/// </summary>
public string GetHashedPassword(string password) {
Encoding encoding = new ASCIIEncoding();
byte[] hash = new MD5CryptoServiceProvider().ComputeHash(encoding.GetBytes(password));
StringBuilder builder = new StringBuilder();
for (int i = 0; i < hash.Length; i++) {
builder.Append(hash[i].ToString("X2"));
}
return builder.ToString();
}
You just made my day. I was desperately trying to figure out the differences between System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile and System.Security.Cryptography.MD5CryptoServiceProvider.Create().ComputeHash. Your post answered that!