密码验证8位数字,包含大写字母、小写字母和一个特殊字符。

6

我写了一个方法,让用户输入密码并且要符合以下规格:

1. 至少8个字符长

2. 包含大写字母

3. 包含小写字母

4. 包含特殊字符

但是当我输入时,输出结果没有考虑特殊字符,会出现错误。

这是我的代码:

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.print("Please enter a given  password : ");
    String passwordhere = in.nextLine();
    System.out.print("Please re-enter the password to confirm : ");
    String confirmhere = in.nextLine();
    System.out.println("your password is: " + passwordhere);

    while (!passwordhere.equals(confirmhere) || !isValid(passwordhere)) {
        System.out.println("The password entered here  is invalid");
        System.out.print("Please enter the password again.it must be valid : ");
        String Passwordhere = in.nextLine();
        System.out.print("Please re-enter the password to confirm : ");

    }
}

public static boolean isValid(String passwordhere) {

    if (passwordhere.length() < 8) {
        return false;
    } else {

        for (int p = 0; p < passwordhere.length(); p++) {
            if (Character.isUpperCase(passwordhere.charAt(p))) {
            }
        }
        for (int q = 0; q < passwordhere.length(); q++) {
            if (Character.isLowerCase(passwordhere.charAt(q))) {
            }
        }
        for (int r = 0; r < passwordhere.length(); r++) {
            if (Character.isDigit(passwordhere.charAt(r))) {
            }
        }
        for (int s = 0; s < passwordhere.length(); s++) {
            if (Character.isSpecialCharacter(passwordhere.charAt(s))) {
            } 
            }
            return true;
        }
}

此外,另一个问题是,例如,假设用户将bob123作为其密码输入。
我该如何让循环告诉用户它需要什么才能成为正确的密码?
在上面的示例中,缺少一个大写字母和一个符号(*&amp; ^..等)。
我该如何添加此内容以每次用户创建密码时打印出来,并直到他们获得通过代码的所有规格的正确密码?

@Programminnoob 请针对正则表达式密码验证进行一些研究,了解后告知我。Character.isSpecialCharacter不是一个函数,检查特殊字符的最简单方法是使用正则表达式,因此您最好学习如何正确地执行此操作。 - OneCricketeer
请参考 https://dev59.com/0Gcs5IYBdhLWcg3wYzH6#12885952。 - OneCricketeer
这将替换掉您不存在的Character.isSpecialCharacter - OneCricketeer
我应该将它用作单独的方法还是将其作为循环?@cricket_007 - Progamminnoob
我并不认为正则表达式的方法可行。我理解的要求是“至少一个大写字母,至少一个小写字母和至少一个特殊字符”。这很难用正则表达式来表达。 - Stephen C
显示剩余4条评论
5个回答

15

您应该清楚地说明您的要求,我不知道您的要求。请查看我的下面解决方案。

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.print("Please enter a given  password : ");
    String passwordhere = in.nextLine();
    System.out.print("Please re-enter the password to confirm : ");
    String confirmhere = in.nextLine();

    List<String> errorList = new ArrayList<String>();

    while (!isValid(passwordhere, confirmhere, errorList)) {
        System.out.println("The password entered here  is invalid");
        for (String error : errorList) {
            System.out.println(error);
        }

        System.out.print("Please enter a given  password : ");
        passwordhere = in.nextLine();
        System.out.print("Please re-enter the password to confirm : ");
        confirmhere = in.nextLine();
    }
    System.out.println("your password is: " + passwordhere);

}

public static boolean isValid(String passwordhere, String confirmhere, List<String> errorList) {

    Pattern specailCharPatten = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
    Pattern UpperCasePatten = Pattern.compile("[A-Z ]");
    Pattern lowerCasePatten = Pattern.compile("[a-z ]");
    Pattern digitCasePatten = Pattern.compile("[0-9 ]");
    errorList.clear();

    boolean flag=true;

    if (!passwordhere.equals(confirmhere)) {
        errorList.add("password and confirm password does not match");
        flag=false;
    }
    if (passwordhere.length() < 8) {
        errorList.add("Password lenght must have alleast 8 character !!");
        flag=false;
    }
    if (!specailCharPatten.matcher(passwordhere).find()) {
        errorList.add("Password must have atleast one specail character !!");
        flag=false;
    }
    if (!UpperCasePatten.matcher(passwordhere).find()) {
        errorList.add("Password must have atleast one uppercase character !!");
        flag=false;
    }
    if (!lowerCasePatten.matcher(passwordhere).find()) {
        errorList.add("Password must have atleast one lowercase character !!");
        flag=false;
    }
    if (!digitCasePatten.matcher(passwordhere).find()) {
        errorList.add("Password must have atleast one digit character !!");
        flag=false;
    }

    return flag;

}

0
我不确定为什么当我输出时,输出结果没有考虑特殊字符并抛出了错误。
提示:请看这个片段:
    for (int p = 0; p < passwordhere.length(); p++) {
        if (Character.isUpperCase(passwordhere.charAt(p))) {
        }
    }

当它看到大写字母时,它会做什么?

提示2:我认为您需要计算各种字符类中的字符数,然后...

如何让循环告诉用户需要什么才能成为正确的密码?例如,上面的示例缺少一个大写字母和一个符号(*&^..etc)

提示:您的isValid方法需要向某人或某物“说明”密码无效的原因。考虑它如何实现。(提示2:我可以想出三种不同的方法:异常、返回值、打印)


它循环检查密码中是否含有大写字母..? - Progamminnoob
对于 Stephen 评论的第二部分,我应该在循环内添加一个打印语句,例如:'for (int p = 0; p < 'passwordhere.length(); p++) {' 'if (Character.isUpperCase(passwordhere.charAt(p))) {' ' System.out.println("密码必须包含大写字母。");' } - Progamminnoob
我阅读了你说的内容,但仍然不太确定如何实现它 @cricket_007 - Progamminnoob
@Programminnoob,你觉得 password.matches("[a-zA-Z\d]{8}") 有意义吗?如果不懂,请继续阅读。 - OneCricketeer
是的,这是有道理的,它表示所有小写和大写字母,但符号呢 :o @cricket_007 - Progamminnoob
显示剩余5条评论

0

使用此Bean验证库进行密码验证:

https://github.com/ankurpathak/password-validation https://mvnrepository.com/artifact/com.github.ankurpathak.password/password-validation

它提供了许多约束条件来处理密码验证等问题,未来还将添加更多:

  1. ContainDigit:验证密码是否包含指定数量的数字。
  2. ContainLowercase:验证密码是否包含指定数量的小写字母。
  3. ContainSpecial:验证密码是否包含指定数量的特殊符号。
  4. ContainUppercase:验证密码是否包含指定数量的大写字母。
  5. NotContainWhitespace:验证密码中不应包含任何空格。
  6. PasswordMatches:验证密码和确认密码是否相等。您可以使用标志showErrorOnConfirmPassword(默认为true)将约束条件移动到确认密码字段。

所有约束条件默认情况下都会忽略空白,因此它将由NotBlank标准bean验证约束单独报告,可以使用每个约束条件的ignoreBlank(默认为true)标志关闭。

使用该库的小例子如下:

    @PasswordMatches
    public class PasswordDto {
     @Size(min = 8, max = 30)
     @NotContainWhitespace
     @ContainSpecial
     @ContainDigit
     private String password;
     @NotBlank
     private String confirmPassword;
    }


-1

嗨,请查看以下代码,它可能会对你有所帮助

public static void main(String[] args) {

    Scanner in = new Scanner(System.in);
    System.out.print("Please enter a given  password : ");
    String passwordhere = in.nextLine();
    System.out.print("Please re-enter the password to confirm : ");
    String confirmhere = in.nextLine();
    System.out.println("your password is: " + passwordhere);
    List<String> errorList=isValid(passwordhere,confirmhere);
    while (!errorList.isEmpty()) {
        System.out.println("The password entered here  is invalid");
        for(String error : errorList){
            System.out.println(error);
        }
        String Passwordhere = in.nextLine();
        System.out.print("Please re-enter the password to confirm : ");

    }

}

public static List<String> isValid(String passwordhere, String confirmhere) {

    List<String> errorList = new ArrayList<String>();

    Pattern specailCharPatten = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
    Pattern UpperCasePatten = Pattern.compile("[A-Z ]");
    Pattern lowerCasePatten = Pattern.compile("[a-z ]");
    Pattern digitCasePatten = Pattern.compile("[0-9 ]");

    if (!passwordhere.equals(confirmhere)) {
        errorList.add("password and confirm password does not match");
    }
    if (passwordhere.length() <= 8) {
        errorList.add("Password lenght must have alleast 8 character !!");
    }
    if (!specailCharPatten.matcher(passwordhere).find()) {
        errorList.add("Password must have atleast one specail character !!");
    }
    if (!UpperCasePatten.matcher(passwordhere).find()) {
        errorList.add("Password must have atleast one uppercase character !!");
    }
    if (!lowerCasePatten.matcher(passwordhere).find()) {
        errorList.add("Password must have atleast one lowercase character !!");
    }
    if (!digitCasePatten.matcher(passwordhere).find()) {
        errorList.add("Password must have atleast one digit character !!");
    }

    return errorList;

}

这段代码可以正常工作,但如果我设置的密码是像Bob123这样的密码,并且它没有特殊字符,它会告诉我需要一个特殊字符,但然后它不让我重新开始输入密码。我该如何修复它以重新开始第一个问题并让用户输入新密码? - Progamminnoob

-1
import javax.swing.JOptionPane;

    public class Validation {   

    static String password;

    public static boolean IsValidInput(String s) {

     boolean status = false;    
     char [] array = s.toCharArray();
     int lower=0, upper=0, digits=0;

     if (s.length() > 8) 
     status = true;

      for ( int i = 0;  i < array.length; i++) {
       if(Character.isDigit(array[i]))
          digits++;
       if(Character.isLowerCase(array[i]))
          lower++;
       if(Character.isUpperCase(array[i]))
          upper++;
     }

       if ( !(lower  > 0 ))
       status = false;

       if ( !(upper  > 0 ))
       status = false;

       if ( !(digits > 0 ))
       status = false;

       return status;
     }     

     public static void  setPassword(String p) {
     if (IsValidInput(p)) {
      password = p;
     JOptionPane.showMessageDialog( null, " Your Password is accepted -" + p);
     }

     else {
     password ="";
     JOptionPane.showMessageDialog( null, " Your  Password is  not accepted -" + p);
     }
     }

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接