Friday, June 27, 2008

How to implement MD5 encryption in C#.

The way is very simple shown below.

System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bs = System.Text.Encoding.UTF8.GetBytes(password);
bs = x.ComputeHash(bs);
System.Text.StringBuilder s =
new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
password = s.ToString();

And also there is the simplest and fastest version that actually works

public static string EncodePassword(string password)
{
byte[] original_bytes = System.Text.Encoding.ASCII.GetBytes(password);
byte[] encoded_bytes = new MD5CryptoServiceProvider().ComputeHash(original_bytes);
StringBuilder result = new StringBuilder();
for (int i=0; i < encoded_bytes.Length; i ) {
result.Append(encoded_bytes[i].ToString("x2"));
}
return result.ToString();
}

0 comments: