2013-10-04 233 views
1

我有一个与我的winforms程序相关的数据库。它存储名称,usertype,哈希和盐。我排序了注册和写作细节,但我不知道如何将盐(从数据库读取时)作为变量保存。这里是我的代码:从数据库检索盐

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

正如你可以看到,它的返回选项,即“+ userNameBox.Text +‘‘’从哪里登录名= SELECT DISTINCT盐’”。我如何将盐保存为要返回的变量?

+1

这是容易受到SQL注入式攻击。它实际上是乞求被黑客攻击。 –

+0

但即时使用盐和哈希?那么我如何返回盐? –

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

谢谢:)虽然字符串结果;从来没有使用过,所以我删除它,但它仍然有效!这是编写代码的更安全的方式吗? –

+0

是的,这更安全。 **总是**使用查询参数将用户数据放入查询中,并且在抛出异常的情况下使用'使用'块来确保您的数据库连接关闭。 –

+0

哦,选择必须改为sql。但是谢谢你,我现在学了2件事! :) –