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

此方法會檢查某些強式密碼的特性,並以密碼未通過哪些檢查的資訊來更新字串參數。

密碼可用於安全系統中,以授權使用者。 不過,未經授權的使用者必須難以猜測密碼。 攻擊者可以使用字典攻擊程式,逐一查看字典中的所有字組 (或不同語言的多個字典),並測試是否有任何字組用作使用者的密碼。 弱式密碼如快速猜到的「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 應用程式安全性

您可以藉由新增額外的複雜度檢查來改善 ValidatePassword 函式的精確度:

  • 將密碼及其子字串與使用者的名稱、使用者識別碼和應用程式定義的字典進行比較。 此外,在執行比較時,將視覺上類似的字元視為相等。 例如,將字母「l」和「e」視為相當於數字「1」和「3」。

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

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

  • 請勿允許從鍵盤第一排輸入所有符號的密碼。

另請參閱