Solved

ASP.NET Salting and Hash Password

Posted on 2009-06-27
10
869 Views
Last Modified: 2012-05-07
Hello,

I'm looking to see if someone in EE could help me create a small Salt and Hash function so that when a user creates a password it is hashed in the DB. Note, I'm using ASP.NET 3.5 VB and i'm using my own DB store and not the ASP.NET Membership and Role Provider. This application is very small and i would like a way to just hash the password and a way to check against it when a user tries to login.

Username: txtUsername
Password: txtPassword

Button Click: btnCreateUser - this event would create the user in the DB along with there Hashed password.


Thanks in Advance!!!
Button Click: btnLogin - this event would check to see that the Salted password is correct
0
Comment
Question by:asp_net2
  • 6
  • 4
10 Comments
 
LVL 3

Accepted Solution

by:
jbeasle3 earned 500 total points
ID: 24728902
See the attached code for creating the hashed password.  Then after the user keys in the password, hash it, concatenate the salt to the hashed password and compare it to the stored hashed password & salt.  For the code to work, you must import System.Web.Security and System.Security.Crytography into your code file.

The CreateSalt function generates a random number of digits and returns the base 64 string for the number of digits requested (specified by intSize).

The CreatePasswordHash function takes the password keyed by the user and the generated salt, concatenates them together, encrypts it and returns the encrypted value.

You must remember to store the salt as well as the encrypted password in your database.  You must concatenate the salt each time you compare passwords.
    Public Function gfCreatePasswordHash(ByVal vstrPwd As String, ByVal vstrSalt As String) As String

        Dim strSaltAndPwd As String = String.Concat(vstrPwd, vstrSalt)

        Dim strHashedPwd As String = FormsAuthentication.HashPasswordForStoringInConfigFile(strSaltAndPwd, "SHA1")

        Return strHashedPwd

    End Function
 

    Public Function gfCreateSalt(ByVal intSize As Integer) As String

        ' Generate a cryptographic random number using the cryptographic

        ' service provider

        Dim rng As RNGCryptoServiceProvider = New RNGCryptoServiceProvider

        Dim buff() As Byte = New Byte(intSize) {}

        rng.GetBytes(buff)

        ' Return a Base64 string representation of the random number

        Return Convert.ToBase64String(buff)

    End Function

Open in new window

0
 
LVL 4

Author Comment

by:asp_net2
ID: 24729863
Hi jbeasle3,

I added the following information below to my button click event and was wondering how to implement the functions you created to my click event.

Do i have to include the functions in a page_load? Or just add the functions somehow to my click event which i'm not sure how to.


Protected Sub btnAddUser_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddUser.Click
        If Page.IsValid Then

            Dim conn As SqlConnection
            Dim Insertcomm As SqlCommand

            Dim connectionString As String = ConfigurationManager.ConnectionStrings("DemoSql").ConnectionString

            conn = New SqlConnection(connectionString)

            Insertcomm = New SqlCommand("SaltInsert", conn)
            Insertcomm.CommandType = CommandType.StoredProcedure

            Insertcomm.Parameters.Add("@username", System.Data.SqlDbType.VarChar, 50)
            Insertcomm.Parameters("@username").Value = txtUsername.Text

            Insertcomm.Parameters.Add("@passwordhash", System.Data.SqlDbType.VarChar, 128)
            Insertcomm.Parameters("@passwordhash").Value = gfCreatePasswordHash()

            Insertcomm.Parameters.Add("@passwordsalt", System.Data.SqlDbType.VarChar, 128)
            Insertcomm.Parameters("@passwordsalt").Value = gfCreateSalt()

            Try
                conn.Open()

                Insertcomm.ExecuteNonQuery()

            Catch ex As Exception
                ex.Message.ToString()

            Finally
                conn.Close()
            End Try
        End If

    End Sub
0
 
LVL 3

Expert Comment

by:jbeasle3
ID: 24730470
You were almost there.   The salt has to be created first.  Here's how I would do it:

dim strSalt as string

strSalt = gfCreateSalt(5)   'This creates a 5-digit salt
Insertcomm.Parameters.Add("@passwordsalt", System.Data.SqlDbType.VarChar, 128)
Insertcomm.Parameters("@passwordsalt").Value = strSalt

Insertcomm.Parameters.Add("@passwordhash", System.Data.SqlDbType.VarChar, 128)
Insertcomm.Parameters("@passwordhash").Value = gfCreatePasswordHash(strUserPswd, strSalt)  'strSalt was created above and strUserPswd is what the user keyed in

You can put the functions in any module where this code page can see them.  I tend to put them in a common module so any page that needs to can call them.



0
 
LVL 4

Author Comment

by:asp_net2
ID: 24733294
Hi jbeasle3,

Ok, ran into a little problem. After i implement the code you supplied in the last post i'm getting an error message below which i think has to do with passing the name of my Password TextBox inside as a parameter but i could be wrong.

ERROR MESSAGE:

Name 'strUserPswd' is not declared on the following code snippet below.

Insertcomm.Parameters.Add("@passwordhash", System.Data.SqlDbType.VarChar, 128)
Insertcomm.Parameters("@passwordhash").Value = gfCreatePasswordHash(strUserPswd, strSalt)
 'strSalt was created above and strUserPswd is what the user keyed in

The name of my Password TextBox is "txtPassword".

I'm going to post all the code that i currently have thanks to your help just so you can see where i'm at and maybe it was a small mistake on my end.


CODE:

Public Function gfCreatePasswordHash(ByVal vstrPwd As String, ByVal vstrSalt As String) As String
        Dim strSaltAndPwd As String = String.Concat(vstrPwd, vstrSalt)
        Dim strHashedPwd As String = FormsAuthentication.HashPasswordForStoringInConfigFile(strSaltAndPwd, "SHA1")
        Return strHashedPwd
    End Function

    Public Function gfCreateSalt(ByVal intSize As Integer) As String
        ' Generate a cryptographic random number using the cryptographic
        ' service provider
        Dim rng As RNGCryptoServiceProvider = New RNGCryptoServiceProvider
        Dim buff() As Byte = New Byte(intSize) {}
        rng.GetBytes(buff)
        ' Return a Base64 string representation of the random number
        Return Convert.ToBase64String(buff)
    End Function

    Protected Sub btnAddUser_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddUser.Click
        If Page.IsValid Then

            Dim strSalt As String

            Dim conn As SqlConnection
            Dim Insertcomm As SqlCommand

            Dim connectionString As String = ConfigurationManager.ConnectionStrings("DemoSql").ConnectionString

            conn = New SqlConnection(connectionString)

            Insertcomm = New SqlCommand("SaltInsert", conn)
            Insertcomm.CommandType = CommandType.StoredProcedure

            Insertcomm.Parameters.Add("@username", System.Data.SqlDbType.VarChar, 50)
            Insertcomm.Parameters("@username").Value = txtUsername.Text

            Insertcomm.Parameters.Add("@passwordhash", System.Data.SqlDbType.VarChar, 128)
            Insertcomm.Parameters("@passwordhash").Value = gfCreatePasswordHash(strUserPswd, strSalt)
            'strSalt was created above and strUserPswd is what the user keyed in

            strSalt = gfCreateSalt(5)   'This creates a 5-digit salt
            Insertcomm.Parameters.Add("@passwordsalt", System.Data.SqlDbType.VarChar, 128)
            Insertcomm.Parameters("@passwordsalt").Value = strSalt

            Try
                conn.Open()

                Insertcomm.ExecuteNonQuery()

            Catch ex As Exception
                ex.Message.ToString()

            Finally
                conn.Close()
            End Try
        End If

    End Sub
0
 
LVL 3

Expert Comment

by:jbeasle3
ID: 24733806
ok...Just substitute txtPassword.Text for strUserPswd.  Also, it's VERY IMPORTANT that you do the salt routine BEFORE the password hash because the password routine uses it.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 4

Author Comment

by:asp_net2
ID: 24735608
Hi jbeasle3,

That worked out as needed. Now if i wanted to increase the Salt size would i just change the integer in strSalt = gfCreateSalt(5) only?

Also, now i need for a way to login in with the credentials that i created. I can give you my custom login that i created, would you be willing to help me with the login event if i supplied you the code that i have now?

If so, then i will create another post different from this one and supply the link to you so that i can award you 500 points for each post.

Let me know,

0
 
LVL 4

Author Comment

by:asp_net2
ID: 24741875
Hi jbeasle3,

Are you stil able to help with post 24735608? Before i close the ticket i wanted to know if you could help me with authenticating against the password hash and salt in another post. I haven't created the post yet because i would like to award you with the points. Please let me konw so that i can assign points for you on this topic before opening another post about this.

Thanks in advance!!
0
 
LVL 3

Expert Comment

by:jbeasle3
ID: 24742868
I would be happy to do that.
0
 
LVL 4

Author Comment

by:asp_net2
ID: 24744282
Hi jbeasle3,

Thanks, i really appreciate it, the following link is below for the new post. Once i know that you received it then i will close this post. Thanks again very much!!

http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_24532865.html
0
 
LVL 4

Author Closing Comment

by:asp_net2
ID: 31597576
thanks for the help.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article discusses the ASP.NET AJAX ModalPopupExtender control. In this article we will show how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, how to show/display/cal…
Sometimes in DotNetNuke module development you want to swap controls within the same module definition.  In doing this DNN (somewhat annoyingly) swaps the Skin and Container definitions to the default admin selections.  To get around this you need t…
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now