Thursday, November 3, 2011

How to Encrypt Passwords using MD5 in ASP.NET(C#) application

How to Encrypt Passwords using MD5 in ASP.NET(C#) application

Encryption for sensitive data like password is essential in everyday development. MD5 hashing algorithm is one of the most commonly used algorithms in asp.net arena and is one of the best. There are two general classes of encryption: one-way encryption and two-way encryption. Using two-way encryption you can encrypt a text as well as you can decrypt it. But for one-way encryption the difference is you can't decrypt it. MD5 encryption is an example of a one-way encryption algorithm.

This is the common task for every registration page where user put their name & their password. You can encrypt the both or only password & save it into the database. So that no one can read the encrypted password which will increase the application security policy. Here i will show you how you can encrypt password. To make it generic it will be best to add a static class so that you can reuse it over this application. The static function is given below:

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

Now you an encrypted data. Insert it into your database table. So user creation is completed. Now how we can authenticate the valid user? Its easy again send the user input to the md5 method which will return you an encrypted string -- now compare with your database. If matched then the user verified.

No comments:

Post a Comment