How to Hash and Salt Passwords in ASP.NET

Posted by Serge Truth on March 22, 2011 at 9:25 AM


Hash and Salt PasswordsUse a hashing algorithm, such as SHA256, to store passwords. Make sure to salt the hashes. 

Step 1. Compute the Salt

You can compute the salt value by using the RNGCryptoServiceProvider class, as shown in the following code example.

using System.Security.Cryptography;
private static string CreateSalt(int size){
// Generate a cryptographic random number using the cryptographic
// service provider
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
// Return a Base64 string representation of the random number
return Convert.ToBase64String(buff);

Note: If you use the ASP.NET SQL Server membership provider, you can configure it to store password hashes with added salt by setting passwordFormat="Hashed" on the provider configuration. 

Step 2. Combine Password and Salt

Simply concatenate the password and the salt.

Step 3. Hash the Password and the Salt

The following code example shows how to use a hashing algorithm, such as SHA256, to hash data.

using System.Security.Cryptography;
// Create a new instance of the hash crypto service provider.
HashAlgorithm hashAlg = new SHA256CryptoServiceProvider();
// Convert the data to hash to an array of Bytes.
byte[] bytValue = System.Text.Encoding.UTF8.GetBytes(stringDataToHash);
// Compute the Hash. This returns an array of Bytes.
byte[] bytHash = hashAlg.ComputeHash(bytValue);
// Optionally, represent the hash value as a base64-encoded string,
// For example, if you need to display the value or transmit it over a network.
string base64 = Convert.ToBase64String(bytHash);

Step 4. Store the Hash and the Salt

Store the hash and the salt in the location of your choosing. Make sure to store the salt along with the hash, because the salt is necessary for computing hashes when checking user entered passwords.

Adapted from Microsoft patterns & practices guidance.

Topics: developer guidance

Serge Truth

Written by Serge Truth

Serge is a Content Lead here at Security Innovation. He is an IT and Information Security professional, certified by the Committee on National Security Systems Instruction.