我有一个与我的winforms程序相关的数据库。它存储name,usertype,hash和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";
}
}
正如您所看到的,它的返回选择是“从登录中选择DISTINCT Salt,其中Name ='”+ userNameBox.Text +“'”。如何将salt保存为要返回的变量?
答案 0 :(得分: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";
}
}