2013-10-04 78 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件事! :) –