2

我有一个Login form,我还没有对密码做任何事情hashing,我一直在这里和那里阅读关于哈希的内容,但它真的让我感到困惑,并且真的不知道如何在我的登录表单代码中实现它。 我看到的散列代码

Dim bytes() as byte  = System.Text.Encoding.UTF8.GetBytes(stringPassword);
dim  hashOfBytes() as byte = new System.Security.Cryptography.SHA1Managed().ComputeHash(bytes)
Dim strHash as string = Convert.ToBase64String(hashOfBytes)

转换回字节

hashOfBytes = Convert.FromBase64String(strHash)

**我的登录表单代码**

Using conn As New MySqlConnection("Server = localhost; Username= root; Password =; Database = forms")
    Using cmd
        With cmd
            MsgBox("Connection Established")
            .Connection = conn
            .Parameters.Clear()
            .CommandText = "SELECT * FROM users WHERE BINARY Username = @iUsername AND Password = @iPassword"
            .Parameters.Add(New MySqlParameter("@iUsername", txtUser.Text))
            .Parameters.Add(New MySqlParameter("@iPassword", txtPass.Text))

        End With
        Try
            conn.Open()
            dr = cmd.ExecuteReader()
        Catch ex As MySqlException
            MsgBox(ex.Message.ToString())
        End Try
    End Using
End Using

If dr.HasRows = 0 Then

    MsgBox("Invalid user")
    Conn.Close()

Else


    Start.Show()
    Conn.Close()


End If
End Sub
4

1 回答 1

1

您应该将密码的哈希值存储在表的密码字段中。
然后您搜索用户和密码哈希,而不是直接搜索从输入框中获取的密码。

但是,您的代码仍然会失败,因为您在处理连接后尝试使用 MySqlDataReader。移动 Using 块内的行检查

 Dim strHash as string = Convert.ToBase64String(hashOfBytes)
 .....
 Dim userIsValid as Boolean = False
 Using conn As New MySqlConnection(.........)
 Using cmd
    ....
        .Parameters.Add(New MySqlParameter("@iPassword", strHashPass))
        Try
            conn.Open()
            dr = cmd.ExecuteReader()
            userIsValid = dr.HasRows
        Catch ex As MySqlException
            MsgBox(ex.Message.ToString())
        End Try
  End Using
  End Using

  if userIsValid then
      .....
  else
      .....
  End
于 2012-11-14T09:10:54.233 回答