Passay Tutorial on Passay M of N rules

many times a password policy mandated compliance to minimum rules out of given rules such as a password must be compliant with at least m of n 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 at least three of the following: upper, lower, digit or symbol.

example

the below example shows the validation of a password against above policy using passay library.

import java.io.filenotfoundexception;
import java.io.ioexception;

import org.passay.charactercharacteristicsrule;
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) throws filenotfoundexception, ioexception {
      //rule 1: password length should be in between 
      //8 and 16 characters
      rule rule1 = new lengthrule(8, 16);        
      //rule 2: no whitespace allowed
      rule rule2 = new whitespacerule();        
      charactercharacteristicsrule rule3 = new charactercharacteristicsrule();        
      //m - mandatory characters count
      rule3.setnumberofcharacteristics(3);        
      //rule 3.a: one upper-case character
      rule3.getrules().add(new characterrule(englishcharacterdata.uppercase, 1));        
      //rule 3.b: one lower-case character
      rule3.getrules().add(new characterrule(englishcharacterdata.lowercase, 1));        
      //rule 3.c: one digit
      rule3.getrules().add(new characterrule(englishcharacterdata.digit, 1));        
      //rule 3.d: one special character
      rule3.getrules().add(new characterrule(englishcharacterdata.special, 1));

      passwordvalidator validator = new passwordvalidator(rule1, rule2, rule3);        
      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.