Sunday, November 25, 2007

How to create salted password hash

We store user passwords in hashed format. A hash function is a one-way data alternation: we create the fingerprint of the data, and the original data can't be retrieved from it.

How to create hash

Take the following steps to create the hashed user password:

  1. Get the user's password
  2. Use a hash function on the plain text (original password)
  3. Store the hashed password in the database for user identification

How to identify the user

Take the following steps to identify a user using her username and password:

  1. Get the user's password
  2. Use a hash function on the plain text (original password)
  3. Read out her stored hashed password from the database. It's identified by her username.
  4. Compare the two (recently generated and stored password) hashed passwords. If they are the same, you can grant access to the user.

What is salt?

Salt is a data we add to the password. This way it's much more harder to break the hash (e.g. get the hashed data).

How to create and store salted hash in C#

There are two ways we can choose:

  • Create our own algorithm
  • Use a library

Using an own security algorithm can be dangerous so I prefer libraries.

System.Security.Cryptography

System.Security.Cryptography in mscorlib contains several hash functions. Here is a usage example:

byte[] data = new byte[DATA_SIZE];
byte[] result;
SHA1 shaM = new SHA1Managed();
result = shaM.ComputeHash(data);

These classes provide hash functions, but they can't create salted hash without own algoritms.

Microsoft Enterprise Library Cryptography Application Block

Enterprise Library can create hashes with salt. No additional algorithms needed. Open Visual Studio.

App.config

Add App.config file to your solution if you don't have one yet. Right-click it, and select Edit Enterprise Library Configuration. If Enterprise Library is not installed on your machine, you won't see this option.

Right-click your App.config node in the tree view and click New/Cryptography Application Block. Select Hash Providers/New/HashAlgorithm Provider. Select your hash algorithm. On the Properties tab, make sure SalEnabled property is True.

Create salted hash

The following code will create a hashed password with Base64 coding. You will be able to copy the value to your database.

byte[] password = UnicodeEncoding.UTF8.GetBytes("plain text password here");
string hashedPassword = Convert.ToBase64String(Cryptographer.CreateHash("SHA512Managed", password));
            Array.Clear(password, 0, password.Length);

Check user password

You can check your salted hash agains the user's password this way:

if (Cryptographer.CompareHash("SHA512Managed", Encoding.UTF8.GetBytes("plaintext password here"), Convert.FromBase64String("password from database here")))
{
             return true;
}
else
{
             return false;
}

 

Link: Hash function
Link: Salt (cryptography)
Link: SHA1Managed Class
Link: Enterprise Library