逐步解說:驗證密碼確實複雜 (Visual Basic)

密碼可以用在安全的系統,以便授權使用者。 然而,密碼必須難以讓未授權使用者猜出。 攻擊者可以使用「字典攻擊」(Dictionary Attack) 程式,這個程式會逐一查看字典 (或多個不同語言的字典) 中的所有字組,並測試是否有任何字組可做為使用者的密碼。 如 "Yankees" 或 "Mustang" 之類的弱式密碼,很快就會被猜出。 如 "?You'L1N3vaFiNdMeyeP@sSWerd!" 之類的強式密碼,則非常不可能被猜出。 密碼保護的系統應該確定使用者選擇強式密碼。

強式密碼是很複雜的 (包含大寫、小寫、數字和特殊字元的混用),而且不是單字。 以下範例會驗證複雜性。

範例

程式碼

''' <summary>Determines if a password is sufficiently complex.</summary> 
''' <param name="pwd">Password to validate</param> 
''' <param name="minLength">Minimum number of password characters.</param> 
''' <param name="numUpper">Minimum number of uppercase characters.</param> 
''' <param name="numLower">Minimum number of lowercase characters.</param> 
''' <param name="numNumbers">Minimum number of numeric characters.</param> 
''' <param name="numSpecial">Minimum number of special characters.</param> 
''' <returns>True if the password is sufficiently complex.</returns> 
Function ValidatePassword(ByVal pwd As String, 
    Optional ByVal minLength As Integer = 8, 
    Optional ByVal numUpper As Integer = 2, 
    Optional ByVal numLower As Integer = 2, 
    Optional ByVal numNumbers As Integer = 2, 
    Optional ByVal numSpecial As Integer = 2) As Boolean 

    ' Replace [A-Z] with \p{Lu}, to allow for Unicode uppercase letters. 
    Dim upper As New System.Text.RegularExpressions.Regex("[A-Z]")
    Dim lower As New System.Text.RegularExpressions.Regex("[a-z]")
    Dim number As New System.Text.RegularExpressions.Regex("[0-9]")
    ' Special is "none of the above". 
    Dim special As New System.Text.RegularExpressions.Regex("[^a-zA-Z0-9]")

    ' Check the length. 
    If Len(pwd) < minLength Then Return False 
    ' Check for minimum number of occurrences. 
    If upper.Matches(pwd).Count < numUpper Then Return False 
    If lower.Matches(pwd).Count < numLower Then Return False 
    If number.Matches(pwd).Count < numNumbers Then Return False 
    If special.Matches(pwd).Count < numSpecial Then Return False 

    ' Passed all checks. 
    Return True 
End Function 

Sub TestValidatePassword()
    Dim password As String = "Password" 
    ' Demonstrate that "Password" is not complex.
    MsgBox(password & " is complex: " & ValidatePassword(password))

    password = "Z9f%a>2kQ" 
    ' Demonstrate that "Z9f%a>2kQ" is not complex.
    MsgBox(password & " is complex: " & ValidatePassword(password))
End Sub

編譯程式碼

傳遞包含該密碼的字串,呼叫這個方法。

這個範例需要:

安全性

如果您要跨網路移動密碼,則您需要使用安全方法傳送資料。 如需詳細資訊,請參閱 ASP.NET Web Application Security

您可以加入其他複雜性檢查,改善 ValidatePassword 函式的精確性:

  • 對照使用者名稱、使用者識別項和應用程式定義的字典,比較密碼和子字串。 此外,當執行比較時,將看起來類似的字元視為對等字元。 例如,將字母 "l" 和 "e" 視為與數字 "1" 和 "3" 對等。

  • 如果只有一個大寫字元,請確定它不是密碼的第一個字元。

  • 確定密碼的最後兩個字元是字母字元。

  • 不允許密碼的所有符號,都是從鍵盤第一列輸入的。

請參閱

參考

Regex

其他資源

ASP.NET Web Application Security