2017-05-09 141 views
0

我有一個問題,當我運行一個SQL命令,結果是一個哈希密碼SHA 256C#複製 '' 與SQL Server 2008

密碼數據庫:用C#返回"Z?VU??u2???f?[??\n?Mn??=1???<3?\v?"

密碼查詢後:"Z?VU??u2???f?[??\ \n?Mn??=1???<3?\ \v?"(我把一個空間,因爲它是由頁面刪除)

這是我的代碼:

byte[] data = System.Text.Encoding.ASCII.GetBytes(txtPassword.Text); 
data = new System.Security.Cryptography.SHA256Managed().ComputeHash(data); 

String hash = System.Text.Encoding.ASCII.GetString(data); 

SqlDataAdapter da = new SqlDataAdapter(); 

string Command = "Select * From Users where Status=1 and Username='" + txtUser.Text + "'" + " and Password='" + hash + "'"; 
da.SelectCommand = new SqlCommand(Command, Database.Connection); 

da.Fill(dsResult); 

if (dsResult.Tables[0].Rows.Count != 0) 
{ 
    DoSomething(); 
} 

我看到的錯誤,當我嘗試這個

Select Password 
From Users 
Where Status = 1 
    And Username = '" + txtUser.Text + "'" 

,結果是密碼,但有重複\

在SQL Server Management Studio中,這個查詢:

Select * 
From Users 
Where Status = 1 
    And Username = 'Rick' 
    And Password = 'Z?VU??u2???f?[??\n?Mn??=1???<3?\v?' 

完美。

謝謝。

編輯:注射改變。

新代碼:

   SqlDataReader da; 
       string Command= @"Select * From Users where Status=1 and [email protected] and [email protected]"; 
       SqlCommand cmd = new SqlCommand(Command, Database.Connection); 
       cmd.Parameters.Add("@Password", SqlDbType.NVarChar).Value = "Z?VU??u2???f?[??\n?Mn??=1???<3?\v?"; 
       cmd.Parameters.Add("@User", SqlDbType.NVarChar).Value = txtUsuario.Text.Replace(" ", ""); 
       da = cmd.ExecuteReader(); 
       if (da.HasRows) 
       { 
        da.Read(); 
        DoSomething(); 
       } 

但問題仍然存在。另外,在C#執行查詢,解釋,在數據庫中的密碼具有雙斜槓,然後它永遠不會與輸入密碼

+0

你嘗試設置參數的命令,而不是傳遞直接值? –

+2

[SQL注入警報](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - 你應該**不**連接你的SQL語句 - 使用**參數化查詢**,而不是避免SQL注入 - 檢查[小Bobby表](https://xkcd.com/327/) –

+1

複製反斜槓是**標準C#**行爲 - 這並不罕見或導致關心。反斜槓被複制以表明你真的想要一個反斜槓 - 否則它將被解釋爲一個**轉義序列**(與下一個字符一起,例如'\ t'是'','\ r'是回車等) –

回答

1

匹配使用SqlParameter您可以發送變量而不丟失數據,避免SQL Injection這樣的:

string insertString = @"Select * From Users where Status=1 and Username='Rick' and [email protected]"; 
SqlCeCommand cmd = new SqlCeCommand(insertString, c); 
cmd.Parameters.Add("@pass", SqlDbType.NVarchar).Value = "Z?VU??u2???f?[??\n?Mn??=1???<3?\v?"; 
//And the rest 
+0

謝謝你讓我知道注射。我做了一些改變,但問題仍然存在。 當C#執行查詢解釋數據庫中的密碼具有雙斜線時,它永遠不會與輸入的密碼匹配 – NachoRuba