vb.net - 验证生成的密码是否包含必要的字符
问题描述
我正在创建的应用程序需要一点帮助。它只是一个简单的密码生成器。我的应用程序生成密码没有问题,但我需要添加一个步骤来检查: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 限制它。您应该鼓励使用字母、数字、大写字母等的组合。
南多式
推荐阅读
- node.js - 从等待返回的最佳实践
- laravel - Laravel / VueJs 2 最新更改未在实时服务器 IONOS 上呈现
- php - 为什么在从下拉 PHP 和 Ajax 中选择之前出现 0
- python - 通过子字符串信息查找 DataFrame 中的所有行
- firebase - 当页面数据未从 Firebase 完全加载时显示加载指示器/微调器 - Flutter
- javascript - 反应原生应用程序中的重新渲染太多,我该怎么办?
- ios - SwiftUI 中的小部件URL
- php - 从 PHP Web 应用程序连接到本地/本地 Active Directory
- powershell - 向PowerShell中的多个地址发送电子邮件
- c++ - 运行时 C++ 数学无法按预期工作