Wednesday, October 8, 2008

Password Hashing in C#

In normal circumstances when you store passwords in a database in clear text, you simply authenticate a user by finding the password associated with the username supplied and comparing the inputted password with the database value. Authentication with hashed passwords is obviously a little different than the traditional approach. You will create a hash value of the user inputted password and compare it with the already hashed value in your database. If the two hashed strings are equal, go ahead and authenticate the user. For example:
string strUserInputtedHashedPassword = 
             FormsAuthentication.HashPasswordForStoringInConfigFile(
                                      tbPassword.Text, "sha1");
if(strUserInputtedHashedPassword == GetUsersHashedPasswordUsingUserName(tbUserName.Text))
{
   // sign-in successfull
}
else
{
   // sign-in failed
}
 
protected TextBox tbPassword;
  protected Literal liHashedPassword;

  
  private void Page_Load(object sender, System.EventArgs e)
  {
   // Put user code to initialize the page here
  }
  public void btnHash_Click(object sender, EventArgs e)
  {
   if(tbPassword.Text.Length > 0)
   {
    string strHashedPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(tbPassword.Text, "sha1");
    liHashedPassword.Text = "Hashed Password is: " + strHashedPassword;    
   }
  }

No comments: