c# programming

20050320

Salted Password Hash Digest

This method should be used to create salted password hash digests for storage in a database. It will enable you to maintain a more secure user authentication system by not actually keeping the users password in the database.

Passwords should never be saved in clear text in a database. If your database is ever compromised, your users information will not be secure. If you create hash digests of user's passwords, then it will be very difficult for hackers to log in to your user's accounts, as they will still not know the user's passwords.

Salting is a method of hiding duplicate passwords. If multiple users happen to have the same password, without salting, their hash digests will be the same. By salting the password the hash digest is more likely to be different. This method salts the password by prepending a random number to the password. The same salting value is also prepended to the hash digest (surrounded by '$'s to denote it as the salting value) in the database for generating the hash digest again when the user attempts to log in.

Users will authenticate themselves by sending their username and password to your system. You will then look up their user identification, generally a user name or email address, in the database, and pull their salted password hash digest. Next you will extract the salting value from the hash digest. Finally you will prepend the salting value to the password and generate the salted hash digest of the password and compare it to the value of the salted hash digest in the database.

This method uses the SHA-256 algorithm, as the SHA-1 algorithms are no longer considered secure. It generates a random integer between 0 and 99 inclusive for the salt value.

using System; //Random
using System.Security.Cryptography; //SHA256
using System.Text; //Encoding

/// <summary>
/// create SHA-256 hash digest of given string
/// </summary>
/// <param name="password">String to be salted and hashed</param>
/// <returns>String of salt and hash digest</returns>
protected String CreateSaltedHashDigest(String password)
{
  //generate random number for salting
  //uses System.Environment.TickCount as Random Seed
  Random rand = new Random();
  //generate random number between 0 and 99, inclusive
  int salt = rand.Next(99);

  //convert string to byte array
  Encoding ascii = Encoding.ASCII;
  Byte[] encodedBytes = ascii.GetBytes(salt.ToString() + password);

  //initialize SHA-256 method
  SHA256 shaDigest = new SHA256Managed();

  //generate hash digest with prepended salt value
  String sHash = ascii.GetString(shaDigest.ComputeHash(encodedBytes)));
  return ("$" + salt.ToString() + "$" + sHash);
}

0 Comments:

Post a Comment

<< Home