username and password verification vb.net

空扰寡人 提交于 2020-01-11 07:18:33

问题


My program below checks if the userName and the password is in the database( written in visual basic and uses Access database). The program works however, when I type in the userName or password in a different case it still works. For example, if my database has the userName as "john" and the password as "johnspassword", my program accepts the username as "JOHN" and password as "JOHNSPASSWORD".

how do i resolve this problem?

Dim con As New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=C:\Users\jacob\Desktop\MS Office\project.mdb")
    Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM tblUsers WHERE UserID = '" & txtUserName_Field.Text & "' AND userPassword = '" & txtUserPassword_Field.Text & "' ", con)
    con.Open()
    Dim sdr As OleDbDataReader = cmd.ExecuteReader()
    'If the record can be queried, it means passing verification, then open another form.
    Dim empty =
    Me.Controls.OfType(Of TextBox)().Where(Function(txt) txt.Text.Length = 0)
    If empty.Any Then
        MessageBox.Show(String.Format("Please fill in all the fields required"))
    Else
        If (sdr.Read() = True) Then
            MessageBox.Show("The is valid!")
            Form4.Show()
            Me.Hide()
        Else
            MessageBox.Show("Invalid name or password!")
        End If
    End If
    con.Close()
End Sub

回答1:


If you use a hash of the password instead then you solve two problems you have:

  • You should not store passwords as plain text
  • A hash will make the password case-sensitive

The Rfc2898DeriveBytes Class is suitable for creating the hash; you'll need a randomly-generated salt stored in the database for each user too.

There are many sites, e.g., Salted Password Hashing - Doing it Right, with explanations of why salting and hashing are desirable.

You will still have to decide if you need the username to be case-sensitive.

EDIT

It appears that Access doesn't have an efficient (i.e. sargable) way to do a case-sensitive comparison, so you can simply get the username from the database and check it in your program, something like this:

Option Infer On
Option Strict On

Imports System.Data.OleDb
Imports System.Security.Cryptography

Public Class SomeClass

    'TODO: decide on the sizes for the salt and hash
    'TODO: create binary fields in the database of appropriate sizes
    'TODO: consider storing the number of iterations in the database
    Const SALTLENGTH As Integer = 8
    Const HASHLENGTH As Integer = 16
    Const PBKDF2ITERATIONS As Integer = 20000

    Friend Function PBKDF2Hash(password As String, salt As Byte(), iterations As Integer, hashSize As Integer) As Byte()
        Dim hasher As New Rfc2898DeriveBytes(password, salt, iterations)
        Return hasher.GetBytes(hashSize)

    End Function

    Function IsLoginValid(username As String, password As String) As Boolean

        Dim salt(SALTLENGTH - 1) As Byte
        Dim hashedPassword(HASHLENGTH - 1) As Byte
        Dim usernameIsValid = False

        Dim csb As New OleDbConnectionStringBuilder With {
            .Provider = "Microsoft.jet.oledb.4.0",
            .DataSource = "C:\Users\jacob\Desktop\MS Office\project.mdb"
        }

        Using conn As New OleDbConnection(csb.ConnectionString)
            'TODO: use the actual column names
            Using cmd As New OleDbCommand("SELECT UserID, salt, password FROM tblUsers WHERE UserID = ?", conn)
                'TODO: use type of column as specified in the database
                cmd.Parameters.Add(New OleDbParameter With {.OleDbType = OleDbType.VarWChar, .Value = username})
                conn.Open()
                Dim rdr = cmd.ExecuteReader()
                If rdr.HasRows Then
                    rdr.Read()
                    If String.Compare(rdr.GetString(0), username, StringComparison.Ordinal) = 0 Then
                        rdr.GetBytes(1, 0, salt, 0, SALTLENGTH)
                        rdr.GetBytes(2, 0, hashedPassword, 0, HASHLENGTH)
                        usernameIsValid = True
                    End If
                End If

                conn.Close()
            End Using
        End Using

        Dim expectedHash = PBKDF2Hash(password, salt, PBKDF2ITERATIONS, HASHLENGTH)

        If usernameIsValid AndAlso hashedPassword.SequenceEqual(expectedHash) Then
            Return True
        End If

        Return False

    End Function

    Private Sub bnLogin_Click(sender As Object, e As EventArgs) Handles bnLogin.Click
        Dim username = txtUserName_Field.Text
        Dim password = txtUserPassword_Field.Text

        If username.Length = 0 OrElse password.Length = 0 Then
            MessageBox.Show("Please fill in all the fields required.")
            Exit Sub
        End If

        If IsLoginValid(username, password) Then
            ' user has supplied valid credentials
        Else
            MessageBox.Show("Invalid username or password.")
        End If

    End Sub

End Class

Of course, you still have to create the code to put the appropriate data in the database when the user is registered.



来源:https://stackoverflow.com/questions/47713267/username-and-password-verification-vb-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!