此方法检查一些强密码特征,并更新字符串参数,其中包含有关哪些检查密码失败的信息。
密码可用于安全系统来授权用户。 但是,未经授权的用户必须难以猜测密码。 攻击者可以使用 字典攻击 程序,该程序循环访问字典中的所有单词(或不同语言的多个词典),并测试任何单词是否作为用户的密码工作。 可以快速猜测“洋基”或“野马”等弱密码。 更强的密码,例如“?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
编译代码
通过传递包含该密码的字符串来调用此方法。
此示例需要:
- 对命名空间成员 System.Text.RegularExpressions 的访问权限。 如果代码中没有完全限定成员名称,请添加
Imports
语句。 有关详细信息,请参阅 Imports 语句(.NET 命名空间和类型)。
安全
如果要跨网络移动密码,则需要使用安全方法来传输数据。 有关详细信息,请参阅 ASP.NET Web 应用程序安全性。
可以通过添加额外的复杂性检查来提高函数的准确性 ValidatePassword
:
将密码及其子字符串与用户名、用户标识符和应用程序定义的字典进行比较。 此外,在执行比较时,将视觉上类似的字符视为等效字符。 例如,将字母“l”和“e”视为等效于数字“1”和“3”。
如果只有一个大写字符,请确保它不是密码的第一个字符。
确保密码的最后两个字符是字母字符。
密码中的符号不能全部是从键盘第一行输入的符号。