Store password hashes with salt

From Guidance Share

Jump to: navigation, search

- J.D. Meier, Alex Mackman, Michael Dunner, Srinath Vasireddy, Ray Escamilla and Anandha Murukan

If you need to implement a user store that contains user names and passwords, do not store the passwords either in clear text or in encrypted format. Instead of storing passwords, store non-reversible hash values with added salt to mitigate the risk of dictionary attacks.

Note A salt value is a cryptographically strong random number.

Contents

Creating a Salt Value

The following code shows how to generate a salt value by using random number generation functionality provided by the RNGCryptoServiceProvider class within the System.Security.Cryptography namespace.

public static string CreateSalt(int size)
{
  RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
  byte[] buff = new byte[size];
  rng.GetBytes(buff);
  return Convert.ToBase64String(buff);
}

Creating a Hash Value (with Salt)

The following code fragment shows how to generate a hash value from a supplied password and salt value.

public static string CreatePasswordHash(string pwd, string salt)
{
  string saltAndPwd = string.Concat(pwd, salt);
  string hashedPwd =
       FormsAuthentication.HashPasswordForStoringInConfigFile(
                                            saltAndPwd, "SHA1");
  return hashedPwd;
}

More Information

For more information about implementing a user store that stores password hashes with salt, see "How To: Use Forms Authentication with SQL Server 2000" in the "How To" section of "Microsoft patterns & practices Volume I, Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication" at http://msdn.microsoft.com/library/en-us/dnnetsec/html/secnetlpMSDN.asp.

References

Personal tools