Java – how to verify a secure password Regular expression on char []?
This question is a follow-up to this question:
Why is char[] preferred over String for passwords?
This is a good question to understand why char [] is used instead of string; However, it does not explain how to perform password verification on char [] in a secure manner That's what I want to know
In short, I need to check that my password meets the following requirements:
>At least one uppercase letter > at least one lowercase letter > at least one digit > at least one symbol > at least n characters but no more than m
Now I understand how to use regular expressions to perform validation... These answers show how to do this:
> Regexp Java for password validation > Password must be 8 characters including 1 uppercase letter,1 special character,alphanumeric characters
As far as I know, regular expression checking involves using strings It seems unsafe to use them because strings are immutable, so you can't clear them immediately after using them On the other hand, char [] can be cleared
So, how do I validate the password stored in char [] instead of a string?
I can traverse every character, but I have to create every set I want to test Ideally, it would be useful to be able to use regular expressions
In Java, I can check regular expressions in the following ways
String.matches(String regex)
or
Pattern pattern = Pattern.compile(String regex); pattern.matcher(CharSequence testString).matches();
As you can see, neither of these methods supports the direct use of char []
Solution
I'll try to avoid complex regular expressions, and I'll suggest something like –
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; }