演练:验证密码是否复杂 (Visual Basic)

更新:2007 年 11 月

此方法将检查某些强密码特性,并使用有关检查密码失败的信息更新字符串参数。

可在安全的系统中使用密码来向用户授权。但是,密码必须难于被未授权用户猜测出来。攻击者可以使用一种“字典攻击”程序,该程序将遍历一本字典(或不同语言的多本字典)中的所有单词,并测试是否有任何单词就是用户的密码。诸如“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”相同的字符。

  • 如果只有一个大写字符,请确保它不是密码的第一个字符。

  • 确保密码的最后两个字符是字母字符。

  • 不允许这样的密码:其中的所有符号都是通过键盘最上面的一排键输入的。

请参见

参考

Regex

其他资源

ASP.NET Web 应用程序安全性

字符串演练 (Visual Basic)