Sunday 1 March 2015

How to produce hash password or how to prevent SQL Injection?


In your website, you may have a login page which asks things like User id and password. You have to type correct User id and password to get access. But these User id and password is stored somewhere in database in simple text format, which is prone to SQL Injection i.e. by typing some string in place of password, one may get access without using correct password. One solution to this is that always store your passwords in Encrypted or Hashed form. So here is the procedure which tells you, how to produce hash password in ASP.NET:


Step 1
Add namespace:

Using System.Web.Security;

Step 2
On Sign Up or Registration page, you may have a textbox for password say txtPassword, Now use the following statement to generate the hashed password from password typed in txtPassword:

FormsAuthentication.HashPasswordForStoringInConfigFile(string password, string passwordFormat);

Summary:
        // Produces a hash password suitable for storing in a configuration file based
        // on the specified password and hash algorithm.
        //
        // Parameters:
        // password:
        //  The password to hash.
        //
        // passwordFormat:
        // The hash algorithm to use. passwordFormat is a String that represents one
        // of the System.Web.Configuration.FormsAuthPasswordFormat enumeration values.
        //
        // Returns:
        // The hashed password.
        //
        // Exceptions:
        // System.ArgumentNullException:
        // password is null-or-passwordFormat is null.
        //
        // System.ArgumentException:
        //  passwordFormat is not a valid System.Web.Configuration.FormsAuthPasswordFormat
        //  value.


There are basically two passwordFormat used:
  • MD5
  • SHA1
So you can write any one of these statements:

string pass=FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword"MD5");
string pass=FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword"SHA1");

Now you can use variable pass to save the encrypted password to database.


Step 3

Now at  your Login page you may again have field for password say txtPassword. Now again use these statements:
string pass=FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword"MD5");
string pass=FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword"SHA1");

Now compare this encrypted password against the password stored in database. If both are matched then the login is successful otherwise not.



No comments:

Post a Comment