2011-12-18 113 views
1

下面的代碼允許用戶輸入用戶名和密碼登錄以輸入學生的標記。 SQL數據讀取器在進行身份驗證之前從數據庫驗證用戶憑據。如果有人可以通過salting和散列密碼來修改代碼,我將不勝感激。如何加鹽和散列密碼

Dim frm As New MarksEntryFrm 
    Dim flag As Boolean 
    flag = False 
    If cboForm.Text = "" Or cboAcadYear.Text = "" Or cboSubjCode.Text = "" Or txtUserName.Text = "" Or txtPassword.Text = "" Then 
     MessageBox.Show("Please any of the fields cannot be left blank", "Blank fields", MessageBoxButtons.OK, MessageBoxIcon.Error) 
    Else 
     cmd = New SqlCommand("Select a.Form,a.AcademicYear,b.SubjectID,b.UserID,b.Password,c.Term from StudentDetails.Programmes a, StudentDetails.Subjects b,RegistrationDetails.Registration c where b.SubjectID='" & cboSubjCode.SelectedItem & "' and b.UserID='" & txtUserName.Text & "' and b.Password='" & txtPassword.Text & "' collate Latin1_General_CS_AS", cn) 
     cmd.Parameters.AddWithValue("@UserID", txtUserName.Text) 'protects the database from SQL Injection 
     cmd.Parameters.AddWithValue("@Password", txtPassword.Text) 'protects the database from SQL Injection 

     dr1 = cmd.ExecuteReader 
     ctr = ctr + 1 
     If dr1.Read Then 
      frm.Show() 
      ctr = 0 
      Hide() 
     ElseIf ctr < 3 Then 
      MessageBox.Show("Incorrect Subject Code,User Name or Password. Please try again.", "Wrong data entered", MessageBoxButtons.OK, MessageBoxIcon.Asterisk) 
     Else 
      MsgBox("Unathorized access. Aborting...") 
      Close() 
     End If 
     dr1.Close() 
    End If 
End Sub 
+3

哈希與SQL注入無關。您需要了解如何正確使用參數。 (你還需要散列和鹽) – SLaks 2011-12-18 17:51:47

+0

感謝你的指導 – Akaglo 2011-12-18 17:54:08

回答

1

附: Akaglo,檢查是否有空字段的更好方法是使用String.IsNullOrEmpty()方法。你的方法不會檢測到任何空字符。

+0

請特別指出我應該如何在我的代碼中使用String.IsNullOrEmpty()方法。如果你能的話,我會很感激,如果你能爲我做這件事。 – Akaglo 2011-12-18 23:01:11

+0

如果String.IsNullOrEmpty(strName)然後 Messagebox.Show(「字符串爲空」) – Cody8295 2011-12-18 23:52:39

+0

哦,拜託,我非常渴望使用您的建議,但我仍然無法看到如何在編碼中進行處理。請根據您的建議編輯我的代碼。提前致謝。 – Akaglo 2011-12-19 17:30:36

1

使用參數化查詢

Dim cmdText As String = _ 
        "INSERT INTO Customer(UserName, [Password]) VALUES (@UserName,@Password)" 
    Dim cmd As SqlCommand = New SqlCommand(cmdText, con) 
    With cmd.Parameters 
     .Add(New SqlParameter("@UserName", txtUserName.Text)) 
     .Add(New SqlParameter("@Password", txtPassword.Text)) 
    End With 
+1

他仍然需要散列。 – SLaks 2011-12-18 18:00:17

0

在.NET成員資格提供程序中,您將得到應由正確實現的.NET庫提供的散列和播種。這恕我直言是非常喜歡滾動你自己的解決方案。有一個introduction to membership here

如果你喜歡做你的實現種子和哈希部分不是非常複雜。種子化可以像在散列之前向原始密碼添加隨機字符串一樣簡單。然後將散列和種子存儲在數據庫中。當用戶提供密碼時,您只需讀取種子並比較哈希值。請注意,當您爲加密目的製作隨機字符串時,您不應該依賴Random,而應該使用 cryptographically secure random generatorSystem.Security.Cryptography還包含許多適合的散列算法(sha1,sha256或類似)的實現。

再說一遍:在我看來,您應該使用SqlMembershipProvider來解決方案,以避免重新實現安全性關鍵的東西。

+0

您能詳細解釋一下* SqlMembershipProvider *,也許知道一篇文章朝那個方向走得更遠一點? – 2011-12-18 22:04:02

+0

SqlMembershipProvider只是使用MS SQL作爲用戶存儲的成員資格提供程序的具體化。它非常靈活,似乎提供了所需的功能。成員資格是一個很大的話題,但msdn提供了信息http://bit.ly/sF9Ic8。要獲得更多關於會員資格的信息,我認爲一個單獨的問題是適當的。 – faester 2011-12-19 09:25:20