Thursday, March 22, 2012

Simple Encryption

Whats the easiest way to encrypt a password and put it in the database?I would look into Hashing the password. this way the hash is stored inside the database and when needed the system would pull the hash from the database and compare it against a hash of the text entered by the user.
How would I hash it?
Try this,
public static string EncodePassword(string password)
{
// First we need to turn our password into a byte array
byte[] data = System.Text.Encoding.Unicode.GetBytes(password);

// Now generate a basic hash
MD5 md5 = new MD5CryptoServiceProvider();

byte[] result = md5.ComputeHash(data);

return System.Text.Encoding.ASCII.GetString(result, 0, result.Length);
}


The simple way is by using FormsAuthentication.HashPasswordForStoringInConfigFile(pwd, "MD5"), where pwd is a string containing the unencrypted password and MD5 is the algorithm (alternatively SHA1 can be used as well). For better security, I recommend to use hashing with salt. In that case, you store two values for each user: a random salt and the hashed salt + password. To check the user's credentials at login time, retrieve the hash, concat it with the entered password and hash it to compare that value with the stored hash value.

Salting:

RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buf = new byte[16];
rng.GetBytes(buf);
string salt = Convert.ToBase64String(buff);

Then use FormsAuthentication.HashPasswordForStoringInConfigFile(salt + pwd) to hash the salted password.

0 comments:

Post a Comment