Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从数据库中检索salt_C#_Sql_Sql Server - Fatal编程技术网

C# 从数据库中检索salt

C# 从数据库中检索salt,c#,sql,sql-server,C#,Sql,Sql Server,我有一个与我的winforms程序关联的数据库。它存储名称、用户类型、哈希和salt。我对注册和写入细节进行了排序,但我不知道如何将salt(从数据库读取时)保存为变量。这是我的密码: public string getSalt() { SqlConnection connection = new SqlConnection(@"server=.\SQLEXPRESS; database=loginsTest;Trusted_Connection=yes");

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

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";
        }
    }

正如您所看到的,它返回的选择是“从Name='”+userNameBox.Text+'”的登录中选择不同的Salt。如何将salt保存为要返回的变量?

这应该可以做到,并且还修复了原始版本中存在的漏洞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";
    }
}

这容易受到sql注入攻击。它实际上是在乞求被黑客攻击,但我在使用盐和散列?那么我该如何归还盐呢?安全问题不在于盐/杂烩(尽管人们也经常出错)。这是构建查询的方式。想想如果我在用户名字段中输入类似的内容会发生什么:
;删除表登录--
要详细说明,使用建议的输入,第一个字符(单引号)将关闭sql语句中的字符串文字。第二个字符(分号)将结束语句,并允许数据库处理附加语句。下一组字符将删除您的表。是的,Sql Server将真正执行该语句。最后两个字符(破折号)注释掉剩余的任何内容,因此语法错误不会阻止Sql Server运行/提交查询。谢谢:)尽管字符串结果是;从未使用过,所以我将其移除,但它仍然有效!这也是一种更安全的代码编写方式吗?是的,这更安全。始终使用查询参数将用户数据放入查询,并使用
using
块确保在引发异常时关闭数据库连接。哦,选择必须更改为sql。但谢谢你,我现在学到了两件事!:)