Monday, June 25, 2007

Hashing Passwords

In many web site you have seen that they reset your password instead of giving your current password. The only reason that they do this is that actually they cannot retrieve your password.
The way that you store passwords in databases it 's really important. If you store all the users and passwords in clear text, if somebody can access to your database she might do what ever she want. Because of this it 's recommended to store passwords in a way that nobody can get it.
In Hash algorithms you cannot get the original value from the hashed value. And It 's approximately impossible to find a value which the hash of that value become the same as your hashed value. (But not 100%). So I 'm going to tell you how you can Hash your password and store that in your database.

In System.Security.Cryptography namespace there is a class named HashAlgorithm which is a base class for all Hashing algorithm classes such as SHA1Managed or MD5 and ...

It has a method named ComputeHash which return a byte[] of hashed value you passed as byte[]. Take a look at these lines:


HashAlgorithm hashAl = HashAlgorithm.Create("MD5");
byte[] myPasswordInBytes = Encoding.Unicode.GetBytes(txtPassword.Text);

byte[] myHashedPassword = hashAl.ComputeHash(myPasswordInBytes);


Now you can store your hashed password in wherever you want.
Notice that next time the user tries to login , you have to again hash the password and compare it with the one it 's stored in Database, like this:


private bool CompareHashPasswords(byte[] hashedNewPass, byte[] hashedPass)
{

if (hashedNewPass == null || hashedPass == null || hashedNewPass.Length != hashedPass.Length)

return false;

for (int i = 0; i <>
{

if (hashedPass[i] != hashedNewPass[i])

return false;

}

return true;

}


Download the sample code:
http://www.tabatabaei.info/csharpsamples/HashPassword.zip

3 comments:

Expertester® said...

Thank you so much for a very clear explaination and sample.

It really help.

vishu said...

IntPtr accessToken = IntPtr.Zero;
it showing token cannot be zero, any idea?

if anybody has idea plz reply me on kvishwanath@moog.com


advance thanks

vishwa

Anonymous said...

good explanation

Gianlu

Italy