验证生成的密码是否包含必要的字符
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了验证生成的密码是否包含必要的字符相关的知识,希望对你有一定的参考价值。
需要一些我正在创建的应用程序的帮助。它只是一个简单的密码生成器。我有应用程序生成密码没有问题,但我需要在显示密码之前添加一个检查步骤:1个大写字母,1个小写字母,1个数字和1个特殊字符。如果密码不包含这些值,则应再次生成密码。
我想保留我的代码,我只是想在最后添加一个步骤。
非常感谢提前。
这是我的代码:
Public Class Form1
Dim AllCharacters As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789?!£$%^&*()_+[];'#,./?><~@:}{|"
Dim r As New Random
Dim charIndex As Integer
Dim finalpassword As String
Dim passwordChars1() As Char = New Char(9) {}
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
For i As Integer = 0 To 9 - 1
charIndex = r.Next(AllCharacters.Length)
passwordChars1(i) = AllCharacters(charIndex)
Next
finalpassword = passwordChars1
passwordbox.Text = finalpassword 'Displays Password on Main Form Window
End Sub
答案
这是您在创建或更改密码时通常执行的操作。我通常使用类似以下函数的东西来验证密码的复杂性:
'PasswordComplexityRegex is a string value I get from a database at login,
'if it is not present then a default one will be use.
Dim PasswordComplexityRegex as String
'MinimunPasswordLenght is also a number stored in a database if not present
'it will use a default, in this case 12.
Public Function validatePassword(ByVal pass As String) As Boolean
Dim pattern As String = "[~`!@#$%^&*()-_=+';:,./<>?]"
If Not (String.IsNullOrEmpty(PasswordComplexityRegex)) Then
pattern = PasswordComplexityRegex
End If
Dim patternRegex As Match = Regex.Match(pass, pattern)
'In this case it checks that the length of the password is >= to 12
If (IsDBNull(MinimunPasswordLenght) Or MinimunPasswordLenght = 0) Then
MinimunPasswordLenght = 12
End If
Return (patternRegex.Success And pass.Length >= MinimunPasswordLenght)
End Function
你总是测试你的正则表达式是关键,它比一些人想象的要复杂一点。
现在使用此功能验证您的密码并确定是否继续。就像是:
If Not validatePassword(txtNewPassword.Text) Then
MsgBox("Password need to be...", vbCritical, "Password not in compliance...")
End If
您应该允许包括Unicode在内的所有字符,并且不应该限制超出严格必要的长度,例如,如果mysql限制它。你应该鼓励字母,数字,大写等的组合。
Nandostyle
以上是关于验证生成的密码是否包含必要的字符的主要内容,如果未能解决你的问题,请参考以下文章