使用regex的密码标准.当前代码不令人惊叹

本文关键字:代码 regex 密码 标准 使用 | 更新日期: 2023-09-27 18:29:29

我有一个密码标准:

密码的最小长度为8个字符。密码必须至少包含以下4个类别中的3个字符:

  1. 英文大写字符(A到Z)

  2. 英文小写字符(a到z)

  3. 数字(0到9)

  4. 非字母数字字符(即标点符号,如@#$%^+()

我正在使用

Regex compareRegex = new Regex(@"^(?=.*[a-z]{1})(?=.*[A-Z]{1}).{7,}$");
Regex numRegex = new Regex(@"[a-zA-Z0-9].{7,}" );
if (compareRegex.IsMatch(strPassword))
{
    int count = txtLoginPassword.Text.IndexOfAny(new char[] { '/', '''', '[', ']', ':', ';', '|', '=', ',', '+', '*', '?', '<', '>', '@', ''"', '!', '#', '$', '%', '^', '&', '(', ')', '_', '-', '~', '`', '.' });
    if (count >= 0)
        return true;
    if (numRegex.IsMatch(strPassword))
        return true;
    else
        return false;
}
else if (numRegex.IsMatch(strPassword))
{
    bool valid = false;
    int count = txtLoginPassword.Text.IndexOfAny(new char[] { '/', '''', '[', ']', ':', ';', '|', '=', ',', '+', '*', '?', '<', '>', '@', ''"', '!', '#', '$', '%', '^', '&', '(', ')', '_', '-', '~', '`', '.' });
    valid = (count >= 0);
    return valid;
}
else
{
    return false
}

但它不起作用。请帮助

使用regex的密码标准.当前代码不令人惊叹

就我个人而言,我只是将其划分为每个标准的单独检查

private static char[] controlCharacters = 
{ 
     '/', '''', '[', ']', ':', ';', '|', '=', ',', '+', '*', '?', '<', '>', '@', 
     ''"', '!', '#', '$', '%', '^', '&', '(', ')', '_', '-', '~', '`', '.' 
};
public static bool ValidPassword(string password)
{
    if (password.Length < 8)
        return false;
    int sets = 0;
    if (Regex.IsMatch(password, "[A-Z]"))
        sets++;
    if (Regex.IsMatch(password, "[a-z]"))
        sets++;
    if (Regex.IsMatch(password, "[0-9]"))
        sets++;
    if (password.IndexOfAny(controlCharacters)>=0)
        sets++;
    return sets > 2;
} 

或者,如果你想要一个不使用正则表达式的优化版本,你可以这样做。

public static bool ValidPassword(string password)
{
    if (password.Length < 8)
        return false;
    bool[] sets = new bool[4];
    foreach (char c in password)
    {
        if(c >= 'A' && c <= 'Z')
            sets[0] = true;
        else if (c >= 'a' && c <= 'z')
            sets[1] = true;
        else if (c >= '0' && c <= '9')
            sets[2] = true;
        else if (controlCharacters.Contains(c))
            sets[3] = true;
        if (sets.Where(b=>b).Count() > 2)
            return true;
    }
    return false;
}

这个只循环遍历字符并跟踪它看到的每种类型,一旦看到每种类型的3个或更多个,它就会返回true。

我使用的正则表达式如下:

^(?=[^'d_].*?'d)'w('w|[!@#$%]){8,20}这允许一个8到20个字符的密码,即:

  • 必须包含复数字符并选择特殊字符([!@#$%]
  • 密码也不能以数字、下划线或特殊字符开头
  • 最后,必须至少包含一个数字

然而,出于您的目的,我可能不想使用regex,而是让代码来处理它:分析密码字符串,每次它从定义的集合中找到小写字符、大写字符、数字或字符时都设置一个int值:如果没有找到,则为0,如果找到,则使用1,这样您只需添加总数,如果总数>2,则可以允许使用密码。

在c#中,您可以根据以下内容测试功能:

using System;
using System.Collections.Generic;
class Program 
{
    static IEnumerable<string> GetPermutations(string value) 
    {
        if (value.Length == 1) 
        {
            yield return value;
        } 
        else 
        {
            for (int i = 0; i < value.Length; ++i) 
            {
                string a = value[i].ToString();
                foreach (string b in GetPermutations(value.Remove(i, 1))) 
                {
                    yield return a + b;
                }
            }
        }
    }
    static int findCharsInString(string chars, string stringIn)
    {
        foreach (string to_find in GetPermutations(chars)) 
        {
            int i = stringIn.IndexOf(to_find);
            if (i != -1)
            {
                return 1;
            }
            return 0;
        }
    }

    static void Main(string[] args) 
    {
        string lowerCase= "abcdefghijklmnopqrstuvwxyz";
        string upperCase= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        string numChars = "0123456789";
        string allowedSpecials = "@#$%^+()[]";
        string password = "MyNotAllowedPassword";
        string validPW  = "1ValidPassword!";
        if ((findCharsInString(lowerCase, password) + findCharsInString(lowerCase, password) + findCharsInString(lowerCase, password)  + findCharsInString(lowerCase, password)) <3)
        {
            //do something to say its an INVALID password
            Console.WriteLine("INVALID pw!!");
        }
        else
        {
            //do something to say its a VALID password
            Console.WriteLine("Valid pw!!");
        }
        if ((findCharsInString(lowerCase, validPW) + findCharsInString(lowerCase, validPW) + findCharsInString(lowerCase, validPW)  + findCharsInString(lowerCase, validPW)) <3)
        {
            //do something to say its an INVALID password
            Console.WriteLine("INVALID pw!!");
        }
        else
        {
            //do something to say its a VALID password
            Console.WriteLine("Valid pw!!");
        }
    }
}

这使您能够单独检查每组,并允许进行更多控制。我让代码尽可能基本,这样你就可以添加函数来代替重复,或者用不同的方法来修改它,以更容易地满足你的需求。如果有什么需要清理或您想要更多信息,请告诉我:)