.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> ASP.NET >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Password encryption in asp.net

Posted By:ASPEvil       Posted Date: July 31, 2014    Points: 200    Category: ASP.NET    URL: http://www.dotnetspark.com  

How to encrypt password before saving those in the database, in ASP.Net.
 

When you have a website where user data are there, like: username, password, address, telephone etc. All these data can be saved directly to the database, but in case of password, it should not be saved directly to the database because of its highly security reason to avoid any kind of misuse, like: getting hacked user account and any other same type of issues.


To avoid this issues we can encrypt the password before they are saved to the database, so even the database gets hacked, the password is not possible to be known.



This article tells how to encrypt password in ASP.Net.

To do this, create one function at the code behind of your asp.net page, as follow:-

[VB.Net code]

Public Shared Function CreateSaltedPasswordHash(ByVal password As String) As String


            ' Generate random salt string


            Dim csp As New RNGCryptoServiceProvider()

            ''''''[changed by me to the below line] Dim saltBytes As Byte() = New Byte(15) {}
            Dim saltBytes As Byte() = New Byte(16) {}

            csp.GetNonZeroBytes(saltBytes)

            Dim saltString As String = Convert.ToBase64String(saltBytes)

            ' Append the salt string to the password

            Dim saltedPassword As String = password & saltString

            ' Hash the salted password



            Dim hash As String = FormsAuthentication.HashPasswordForStoringInConfigFile(saltedPassword, "SHA1")

            ' Append the salt to the hash

            Dim saltedHash As String = hash & saltString

            Return saltedHash

        End Function

[C# code]

public static string CreateSaltedPasswordHash(string password) {
        //  Generate random salt string
RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider();
        // '''''[changed by me to the below line] Dim saltBytes As Byte() = New Byte(15) {}
        byte[] saltBytes = new byte[] {
                16};
        csp.GetNonZeroBytes(saltBytes);
        string saltString = Convert.ToBase64String(saltBytes);
        //  Append the salt string to the password
        string saltedPassword = (password + saltString);
        //  Hash the salted password
        string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(saltedPassword, "SHA1");
        //  Append the salt to the hash
        string saltedHash = (hash + saltString);
        return saltedHash;
    }

 With the above code[VB.Net code], see the line: "Dim hash As String = FormsAuthentication.HashPasswordForStoringInConfigFile(saltedPassword, "SHA1")" OR [C# code] "string hash = FormsAuthentication.HashPasswordForStoringInConfigFile(saltedPassword, "SHA1");" here at the last, I have mentioned"SHA1", it is a encryption method available with DotNet. You can also use any other available encryption method in DotNet, such as: MD5 etc. For example: if you are wanting to use MD5, then just replace that "SHA1" of this line with the word: "MD5" and it is done.

Now, assume, there is a textbox on your asp.net page, named as txt_password, it is the textbox where your website users inputs their password. Now after your users inputs their password value with this textbox, you probably allowing them to click a button, for the final signup process. Then on this button's click event, write down the following code:-

[VB.Net code]
Dim password As String
        password = Class1.CreateSaltedPasswordHash(txt_repeatpassword.Text)
[C# code]

 string password;
password = Class1.CreateSaltedPasswordHash(txt_repeatpassword.Text);
-----------------------

With the above code, I have declared a string object "password" and called password creation function: "CreateSaltedPasswordHash" with the supplied password value of the textbox: txt_password. Then this called function processes this password value of the textbox and return the hashed value and we put this has value with our declared string object: "password". Now this "password" string have the hashed value of the password value which has been entered/inputed by your user, to the "txt_password" textbox. Now, you can save this "password" string object's value directly to your database's password field.

Up to this, was all how to create the hashed password. Now lets see how your users login with your website, with the username and that hashed password value, saved into your database.

To do this, we need to write another function at the code behind of our asp.net webpage. The code is as follow:-
---------------------------
[VB.Net code]
Public Shared Function ValidatePassword(ByVal password As String, ByVal saltedHash As String) As Boolean

' Extract hash and salt string


            Dim saltString As String = saltedHash.Substring(saltedHash.Length - 24)


            Dim hash1 As String = saltedHash.Substring(0, saltedHash.Length - 24)

            ' Append the salt string to the password

            Dim saltedPassword As String = password & saltString

            ' Hash the salted password



            Dim hash2 As String = FormsAuthentication.HashPasswordForStoringInConfigFile(saltedPassword, "SHA1")

            ' Compare the hashes

            Return (hash1.CompareTo(hash2) = 0)

        End Function
---------------------


[C# code]
------------------
public static bool ValidatePassword(string password, string saltedHash) {
        //  Extract hash and salt string
        string saltString = saltedHash.Substring((saltedHash.Length - 24));
        string hash1 = saltedHash.Substring(0, (saltedHash.Length - 24));
        //  Append the salt string to the password
        string saltedPassword = (password + saltString);
        //  Hash the salted password
        string hash2 = FormsAuthentication.HashPasswordForStoringInConfigFile(saltedPassword, "SHA1");
        //  Compare the hashes
        return (hash1.CompareTo(hash2) == 0);
    } 
------------------

Important Note: With the above line: "Dim hash2 As String = FormsAuthentication.HashPasswordForStoringInConfigFile(saltedPassword, "SHA1")" Or string hash2 = FormsAuthentication.HashPasswordForStoringInConfigFile(saltedPassword, "SHA1"); we have useed the word: "SHA1" at the last which tells that the saved password in the format of "SHA1". So if you have used "MD5" method with the password creation method: "CreateSaltedPasswordHash", then replace "SHA1" here with the "MD5" too, else the password check method will not work at all. In one word, the encryption method mentioned in the password creation method: "CreateSaltedPasswordHash" and the password checking method: "ValidatePassword", shuold be same, else the "ValidatePassword" method will never work.

Now we have to check the user is entering the password value, is this correct or not, by comparing the password value for this same user with the datatase, by the "ValidatePassword" method. To do this, use the following code:-

[VB.Net code]
---------------------------------------
If Class1.ValidatePassword(txt_pwd.Text, existing_pwd) = True Then
 '. your code goes here
Else
 '. your code goes here
Endif
---------------------


[C# code]
----------------------
if ((Class1.ValidatePassword(txt_pwd.Text, existing_pwd) == true)) {
    // & your code goes here
}
else {
    // & your code goes here
} 

----------------------

So, if the entered password matches the saved password for that particular user, who entered this password, then with the above code, the if block returns true and you can then go forward with the login process of this particular user; else with the else block, you can perform the actions when a user's entered password does not matched the saved password with the database for that particular user.


Thanks.


 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend