1

我有一个与我的 winforms 程序关联的数据库。它存储名称、用户类型、哈希和盐。我已经对注册和写入细节进行了排序,但我不知道如何将盐(从数据库读取时)保存为变量。这是我的代码:

public string getSalt()
    {
        SqlConnection connection = new SqlConnection(@"server=.\SQLEXPRESS; database=loginsTest;Trusted_Connection=yes");
        connection.Open();
        string selection = "select DISTINCT Salt from Logins where Name = '"+userNameBox.Text+"'";
        SqlCommand command = new SqlCommand(selection, connection);
        if (command.ExecuteScalar() != null)
        {
            connection.Close();
            return selection;
        }
        else
        {
            connection.Close();
            return "Error";
        }
    }

如您所见,它的返回选择是“从登录名中选择 DISTINCT Salt,其中 Name = '"+userNameBox.Text+"'"。如何将盐保存为要返回的变量?

4

1 回答 1

3

这应该可以做到,并且还修复了原始的 sql 注入漏洞:

public string getSalt()
{
    string sql = "select DISTINCT Salt from Logins where Name = @username"; 

    using (var connection = new SqlConnection(@"server=.\SQLEXPRESS; database=loginsTest;Trusted_Connection=yes")) 
    using (var command = new SqlCommand(sql, connection))
    {
        //guessing at the column length here. Use actual column size instead of 20
        command.Parameters.Add("@username", SqlDbType.NVarChar, 20).Value = userNameBox.Text;

        connection.Open();
        return (command.ExecuteScalar() as string) ?? "Error";
    }
}
于 2013-10-04T18:01:59.107 回答