使用COLLATE使SQL密码查询区分大小写

时间:2014-06-27 06:41:34

标签: sql vb.net visual-studio-2013 case-sensitive collate

我在VS2013的VB中使用以下SQL代码。我想使用存储在UserList中的用户数据库创建登录表单。但是查询不区分大小写。如何更改查询字符串以使用COLLATE或任何其他区分大小写的比较

Dim Check As String = _
   "SELECT COUNT(*) AS Expr1 FROM UserList HAVING (Username = '" & _
    _UsernameTextBox.Text & "') AND ([Password]= '" & _PasswordTextBox.Text & _
    "') AND (UserType = '" & User.ToString & "')"

    With search
        .CommandText = Check
        .Connection = cn
        If .ExecuteScalar() = 1 Then
            Me.Hide()
            If User = "Trader" Then

                Trader.Show()
            ElseIf User = "Broker" Then
                Broker.Show()
            ElseIf User = "Corporate" Then
                Corporate.Show()
            ElseIf User = "System" Then
                SystemManager.Show()


            End If
        Else : MsgBox("IncorrectInput")
        End If`

1 个答案:

答案 0 :(得分:3)

   "SELECT COUNT(*) AS Expr1 FROM UserList 
HAVING (Username = @username)  
AND ([Password] COLLATE Latin1_General_CS_AS = @password) 
AND (UserType = @usertype)

"

除了您没有存储密码并与慢盐加密哈希函数(=不可逆加密)进行比较之外,您的查询也容易受到SQL注入(当我使用像“ Jean le Rond d'Alambert“或者只是”d'Alambert“。

另一个错误是当您将密码保存为纯文本时,例如(n)varchar(32),我可以输入一个比那个更长的密码(例如一个句子)==>错误

鉴于您正在编写财务应用程序(“经纪人”,“公司”),SQL注入是一种无法容忍的安全风险。

您可以使用MD5哈希密码(便宜又脏): master.dbo.fn_varbintohexstr(HashBytes('MD5','test'))

你有一个“System.Data.SqlClient.SqlCommand”, 在那里你可以添加一个System.Data.SqlClient.SqlCommand

using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        //
        // Description of SQL command:
        // 1. It selects all cells from rows matching the name.
        // 2. It uses LIKE operator because Name is a Text field.
        // 3. @Name must be added as a new SqlParameter.
        //
        using (SqlCommand command = new SqlCommand(
        "SELECT * FROM Dogs1 WHERE Name LIKE @Name", connection))
        {
        //
        // Add new SqlParameter to the command.
        //
        command.Parameters.Add(new SqlParameter("Name", dogName));
        //
        // Read in the SELECT results.
        //
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            int weight = reader.GetInt32(0);
            string name = reader.GetString(1);
            string breed = reader.GetString(2);
            Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}",
            weight,
            name,
            breed);
        }
        }
    }

如果你从一开始就这样做,那么你以后就不必改变任何东西了。