How to check on a secure password. Regular expressions on char []?

This question is a continuation of the question here:

Why is char [] preferred over String for passwords?

This question is great for understanding why it is useful to use char [] instead of String; however, it does not explain how to safely perform password checking on char []. This is what I would like to learn about here.

Simply put, I need to check if the password meets the following requirements:

  • Contains at least one uppercase letter
  • Contains at least one lowercase letter
  • Contains at least one digit
  • Contains at least one character
  • At least n characters, but no more than m

Now I understand how I can use regular expressions to perform validation ... these answers show how to do this:

, . , , . A char [], , .

, , char [], ?

, , . .

Java .

String.matches(String regex)

Pattern pattern = Pattern.compile(String regex);
pattern.matcher(CharSequence testString).matches();

, char [].

+4
3

, - -

boolean validatePassword(char[] password, int n, int m) {
  if (password == null || password.length < n || password.length > m) {
    return false;
  }
  boolean upper = false;
  boolean lower = false;
  boolean digit = false;
  boolean symbol = false;
  for (char ch : password) {
    if (Character.isUpperCase(ch)) {
      upper = true;
    } else if (Character.isLowerCase(ch)) {
      lower = true;
    } else if (Character.isDigit(ch)) {
      digit = true;
    } else { // or some symbol test.
      symbol = true;
    }
    // This short-circuits the rest of the loop when all criteria are true.
    if (upper && lower && digit && symbol) {
      return true;
    }
  }
  return upper && lower && digit && symbol;
}
+4

char[],

+4

Java regex String - CharSequence. String char[], CharSequence.

+1
source

All Articles