a typical password policy contains a set of rules to check a password if is compliant with organization rules. consider the following policy:
length of password should be in between 8 to 16 characters.
a password should not contain any whitespace.
a password should contains each of the following: upper, lower, digit and a symbol.
example
the below example shows the validation of a password against above policy using passay library.
import java.util.arraylist;
import java.util.list;
import org.passay.characterrule;
import org.passay.englishcharacterdata;
import org.passay.lengthrule;
import org.passay.passworddata;
import org.passay.passwordvalidator;
import org.passay.rule;
import org.passay.ruleresult;
import org.passay.whitespacerule;
public class passayexample {
public static void main(string[] args) {
list<rule> rules = new arraylist<>();
//rule 1: password length should be in between
//8 and 16 characters
rules.add(new lengthrule(8, 16));
//rule 2: no whitespace allowed
rules.add(new whitespacerule());
//rule 3.a: at least one upper-case character
rules.add(new characterrule(englishcharacterdata.uppercase, 1));
//rule 3.b: at least one lower-case character
rules.add(new characterrule(englishcharacterdata.lowercase, 1));
//rule 3.c: at least one digit
rules.add(new characterrule(englishcharacterdata.digit, 1));
//rule 3.d: at least one special character
rules.add(new characterrule(englishcharacterdata.special, 1));
passwordvalidator validator = new passwordvalidator(rules);
passworddata password = new passworddata("microsoft@123");
ruleresult result = validator.validate(password);
if(result.isvalid()){
system.out.println("password validated.");
} else {
system.out.println("invalid password: " + validator.getmessages(result));
}
}
}
output
password validated.