Validate a Password in Java

This post covers various methods to validate a password in Java.


 

We have seen that a character array is preferred over String object for storing highly sensitive information such as user passwords in Java. But if you must use a String to store a password, then you can use any of below methods to validate it:

 

1. Using OWASP Validator

We can use OWASP Validation Regex which are considered to be very safe. Below regular expression requires the password to have 4 to 8 character and should contains numbers, lowercase and uppercase letters.

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,8}$

 
Below is the break down of each component:


^                  # start of the string
(?=.*\d)           # a digit must occur at least once
(?=.*[a-z])        # a lower case letter must occur at least once
(?=.*[A-Z])        # an upper case letter must occur at least once
.{4,8}             # 4-8 character password, both inclusive
$                  # end of the string

 

Here’s complex version which requires password to have 4 to 32 characters and password should satisfy at least 3 out of 4 conditons(uppercase and lowercase letters, numbers and special characters) and should not have more than 2 equal characters in a row.

^(?:(?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))(?!.*(.)\1{2,})[A-Za-z0-9!~<>,;:_=?*+#."&§%°()\|\[\]\-\$\^\@\/]{8,32}$

 

Download   Run Code

Output:

The Password [email protected] is valid

 

2. Another Regular Expression

Here’s another regular expression for validating a password, taken from Stack Overflow thread. This is basically an extension of OWASP Regex seen before. Since every rule is an independent “module”, we can easily add, modify or remove individual rules.

^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,}$

 
Below is the detailed explanation:


^                  # start of the string
(?=.*[0-9])        # a digit must occur at least once
(?=.*[a-z])        # a lower case letter must occur at least once
(?=.*[A-Z])        # an upper case letter must occur at least once
(?=.*[@#$%^&+=])   # a special character must occur at least once
(?=\\S+$)          # no whitespace allowed in the entire string
.{8,16}            # 8-16 character password, both inclusive
$                  # end of the string

 

Download   Run Code

Output:

The Password Java#@#8 is valid

 

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz