java 密码验证 - 添加额外要求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9962382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:04:14  来源:igfitidea点击:

Password validation - adding additional requirments

javavalidationpasswords

提问by rick

I have some code that currently checks for minimum and maximum lentgh. I want to also require uppercase, lowercase, special char, and numeric. Any suggestions on what to add to this or where I can find some examples? I've been Googling and looking thru this forum and have been trying to add the additional password requirments and have been unsuccessful.

我有一些当前检查最小和最大 lentgh 的代码。我还想要求大写、小写、特殊字符和数字。关于添加什么或在哪里可以找到一些示例的任何建议?我一直在谷歌搜索并浏览这个论坛,并一直试图添加额外的密码要求,但没有成功。

This is what I want to require.

这就是我想要的要求。

At least eight characters in length No more than 20 characters in length at least lower-case letter and one upper-case at least one special character from: !@#$%^&*()~`-=_+[]{}|:";',./<>? at least one number [0-9] character Cannot match the account login name or email address

长度至少为 8 个字符长度不超过 20 个字符至少小写字母和一个大写字母至少一个特殊字符来自:!@#$%^&*()~`-=_+[]{ }|:";',./<>? 至少一个数字 [0-9] 字符 无法匹配帐户登录名或电子邮件地址

My current password validation code

我当前的密码验证码

public static final int MIN_PASSWORD_LENGTH = 8;
public static final int MAX_PASSWORD_LENGTH = 20;

public static boolean isAcceptablePassword(String password)
{
    if(TextUtils.isEmpty(password))
        return false;

    int len = password.length();

    if(len < MIN_PASSWORD_LENGTH || len > MAX_PASSWORD_LENGTH)
        return false;

    for(int i = 0; i < len; i++)
    {
        char c = password.charAt(i);
        if (Character.isWhitespace(c))
            return false;
    }

    return true;
}

回答by Luiggi Mendoza

When you're analyzing Stringdata, you should erase the whitespaces on the right and left. This is done by the Strimg#trimfunction like this:

分析String数据时,应擦除左右两侧的空格。这是由这样的Strimg#trim函数完成的:

password = password.trim();

To analize every character of the String, you can transform it to a char array, so it will be easier to fulfill your requirements:

要分析 String 的每个字符,您可以将其转换为 char 数组,因此更容易满足您的要求:

char[] arrPassword = password.toCharArray();

Now you can evaluate a char using these functions: Character#isUpperCase, Character#isLowerCase, Character#isDigit.

现在您可以使用以下函数计算字符:Character#isUpperCase, Character#isLowerCase, Character#isDigit

Last but not least, you can have a String with the special characters you need to check, and check if the actual character you're evaluating is inside that String. This could be achieved using String#indexOfand String#valueOf, this las one to convert the char to a String type.

最后但并非最不重要的是,您可以拥有一个包含您需要检查的特殊字符的字符串,并检查您正在评估的实际字符是否在该字符串内。这可以使用String#indexOfand来实现String#valueOf,这是将 char 转换为 String 类型的方法。

Here is a code sample for all this explanation:

这是所有这些解释的代码示例:

public static final String SPECIAL_CHARACTERS = "!@#$%^&*()~`-=_+[]{}|:\";',./<>?";
public static final int MIN_PASSWORD_LENGTH = 8;
public static final int MAX_PASSWORD_LENGTH = 20;

public static boolean isAcceptablePassword(String password) {
    if (TextUtils.isEmpty(password)) {
        System.out.println("empty string.");
        return false;
    }
    password = password.trim();
    int len = password.length();
    if(len < MIN_PASSWORD_LENGTH || len > MAX_PASSWORD_LENGTH) {
        System.out.println("wrong size, it must have at least 8 characters and less than 20.");
        return false;
    }
    char[] aC = password.toCharArray();
    for(char c : aC) {
        if (Character.isUpperCase(c)) {
            System.out.println(c + " is uppercase.");
        } else
        if (Character.isLowerCase(c)) {
            System.out.println(c + " is lowercase.");
        } else
        if (Character.isDigit(c)) {
            System.out.println(c + " is digit.");
        } else
        if (SPECIAL_CHARACTERS.indexOf(String.valueOf(c)) >= 0) {
            System.out.println(c + " is valid symbol.");
        } else {
            System.out.println(c + " is an invalid character in the password.");
            return false;
        }
    }
    return true;
}

The System.out.println(c + " is an invalid character in the password.");sentence is just to check the result of analyze the actual character.

System.out.println(c + " is an invalid character in the password.");句话只是为了检查分析实际字符的结果。

回答by Adam

How about some good old regular expressions? This seems to work correctly, although might have made slip in the escaping for special char check

一些好的旧正则表达式怎么样?这似乎工作正常,尽管可能在转义特殊字符检查时出错

Pattern[] checks = {
        Pattern.compile("[!@#\$%^&*()~`\-=_+\[\]{}|:\\";',\./<>?]"),
        Pattern.compile("\d+"), 
        Pattern.compile("[A-Z]+"),
        Pattern.compile("[a-z]+"), 
        Pattern.compile("^.{8,20}$") };

for (String test : new String[] { "password", "Password1",
        "Password1&", "toolongtoolongtoolong" }) {
    boolean ok = true;
    for (Pattern check : checks) {
        ok = ok && check.matcher(test).find();
    }
    System.out.println(test + " " + ok);
}

回答by Michael

Stephen is right with a bit of searching you would have found your answers easily around here. But the thread Stephen refers to is using a thirdparty library.

斯蒂芬是对的,稍微搜索一下,您就可以在这里轻松找到答案。但是斯蒂芬提到的线程正在使用第三方库。

If you want to implement this yourself then before starting the for-loop initialize 4 booleans for your requirements with false. While looping check for all four requirements until one is true. Set the corresponding boolean to true.

如果你想自己实现这个,那么在开始 for 循环之前用 false 为你的要求初始化 4 个布尔值。循环检查所有四个要求,直到其中一个为真。将相应的布尔值设置为 true。

How to check the 4 requirements:

如何检查4个要求:

  • The length req you already implemented.
  • Character(yourChar).isLowerCase()
  • Character(yourChar).isUpperCase()
  • Special character: see here: Java String Special character replacement- you can choose a similar approach
  • 您已经实现的长度要求。
  • 字符(yourChar).isLowerCase()
  • 字符(yourChar).isUpperCase()
  • 特殊字符:请参阅此处:Java 字符串特殊字符替换- 您可以选择类似的方法

After the loop check for the 4 booleans and react accordingly.

在循环检查 4 个布尔值后并做出相应的反应。