我在 VB 中有一个登录系统,它对密码进行编码:
'Hash password
'Create salt (randomness)
Dim salt(16) As Byte
Dim rng = New RNGCryptoServiceProvider()
rng.GetBytes(salt)
For Each t In salt
Debug.WriteLine(t.ToString())
Next
'Hash
Dim pbkdf2 = New Rfc2898DeriveBytes(TxtPassword.Text, salt, 10000)
Dim hash As Byte() = pbkdf2.GetBytes(20)
'Combine salt and password
Dim hashBytes(36) As Byte
Array.Copy(salt, 0, hashBytes, 0, 16)
Array.Copy(hash, 0, hashBytes, 16, 20)
'Convert to string
Dim savedPasswordHash As String = Convert.ToBase64String(hashBytes)
之后它将它保存在我的mysql数据库中。
然后有人想登录:
'Fetch the stored value
Dim savedPasswordHash As String = usersRows.GetString("password")
'Extract the bytes
Dim hashBytes() = Convert.FromBase64String(savedPasswordHash)
'Get the salt
Dim salt(16) As Byte
Array.Copy(hashBytes, 0, salt, 0, 16)
For Each t In salt
Debug.WriteLine(t.ToString())
Next
For Each t In hashBytes
Debug.WriteLine(t.ToString())
Next
Debug.WriteLine(savedPasswordHash)
'Compute the hash on the password the user entered
Dim pbkdf2 = New Rfc2898DeriveBytes(TxtPassword.Text, salt, 10000)
Dim hash As Byte() = pbkdf2.GetBytes(20)
'Correct password variable
Dim passwordCorrect As Boolean = True
'Compare the results
Dim hashed(20) As Byte
Array.Copy(hashBytes, 16, hashed, 0, 20)
If Not hashed.Equals(hash) Then
passwordCorrect = False
End If
Debug.WriteLine(passwordCorrect)
一切正常,但与Convert.FromBase64String(savedPasswordHash)
我最初放入的字节数组不同,但savedPasswordHash
与我的原始字符串相同Convert.ToBase64String(hashBytes)
。