0

I've just added in a function to hash and salt passwords which are stored in an Access database "Memo" field.

The hashing/salting works fine, but I can't find anything on the internet which tells me how to then decrypt them.

I did see somewhere that says you can't, but instead have to get the password from the database, then hash the entered password (for a log on screen) and compare the 2 strings. I've tried this, but the 2 strings are then different, so I cannot log in.

The algorithms for creating the hash/salt are

Public Shared Function createRandomSalt() As String

    Dim mix As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!£$%^&*()-_=+{}][@'~#:;?/>.<,\|"
    Dim salt As String = ""

    Dim rnd As New Random

    Dim sb As New StringBuilder

    For i As Integer = 1 To 50
        Dim x As Integer = rnd.Next(0, mix.Length - 1)
        salt &= (mix.Substring(x, 1))
    Next

    Return salt

End Function

Public Shared Function Hash512(ByVal password As String, ByVal salt As String)

    Dim convertedToBytes As Byte() = Encoding.UTF8.GetBytes(password & salt)
    Dim hashType As HashAlgorithm = New SHA512Managed()
    Dim hashBytes As Byte() = hashType.ComputeHash(convertedToBytes)
    Dim hashedResult As String = Convert.ToBase64String(hashBytes)

    Return hashedResult

End Function

Then, when logging in, I'm trying the following

sql = "SELECT * FROM [Users] WHERE [User_ID] = ?"
Dim sCmd As New OleDb.OleDbCommand(sql, mainDBconnection)
sCmd.Parameters.Add("@ID", OleDb.OleDbType.VarChar).Value = txtUser.Text
mainDBadapter = New OleDb.OleDbDataAdapter(sCmd)
mainDBset = New DataSet
mainDBadapter.Fill(mainDBset)

 For Each userRow In mainDBset.Tables(0).Rows
     Dim password As String = ""
     password = mainDBset.Tables(0).Rows(0).Item("Password")

     Dim checkPassword As String = (frmSystemSettings.Hash512(password, frmSystemSettings.createRandomSalt))

      If userRow.Item("User_ID") = txtUser.Text And password = checkPassword Then

Am I doing something wrong? How can I compare the entered password to the encrypted password in the database?

4

1 回答 1

4

问题是您在对输入的密码进行哈希处理时使用了随机盐。由于这与您在将散列存储到数据库时使用的随机盐不同,因此您会得到不同的散列。

您必须执行以下操作:

  1. 在将密码存储到数据库之前创建一个随机盐,用它对密码进行哈希处理并将盐与密码一起存储在数据库中
  2. 当用户输入他的密码时,从数据库中检索该用户的 salt,使用它对输入的密码进行哈希处理,并将结果与​​数据库中的哈希值进行比较。

哦,您似乎从不使用用户输入的密码。在您的代码中,您将数据库中的哈希检索到password中,再次将该哈希哈希到checkpassword并进行比较。当然,您必须对输入的密码进行哈希处理。

于 2017-03-15T12:33:14.053 回答