Passay - Quick Guide



Passay - Overview

Passay is a Java based Password generation and validation library. It provides comprehensive features list in order to validate/generate passwords and is highly configurable.

Passay Components

Passay API has 3 core components.

  • Rule − one or more rules which define a password policy rule set.

  • PasswordValidator − A validator component which validates a password against a given rule set.

  • PasswordGenerator − A generator component which produces passwords to satisfy a given rule set.

Rule overview

Rules are the foundation blocks for both password validation and generation. There are two broad categories of rules:

  • Positive match require that passwords satisfy a rule.

  • Negative match reject passwords that satisfy a rule.

Features

Following are some of the features that Passay library provides.

  • Password Validation − Passay library helps in enforcing a password policy by validating passwords against a configurable rule set. It has a rich set of existing rules for common use-cases. For additional cases, it provides a simple Rule interface to implement the custom rule.

  • Password Generation − It provides a configurable rule set which can be used to generate passwords as well.

  • Command Line Tools − It provides tools to automate password policy enforcement.

  • convenient − Easy to use.

  • Extensible − All Passay components are extensible.

  • Supports Internalization - Passay components are internationalization ready.

Passay - Environment Setup

This chapter will guide you on how to prepare a development environment to start your work with Passay. It will also teach you how to set up JDK on your machine before you set up jsoup −

Setup Java Development Kit (JDK)

You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.

If you are running Windows and have installed the JDK in C:\jdk-24, you would have to put the following line in your C:\autoexec.bat file.

set PATH=C:\jdk-24;%PATH% 
set JAVA_HOME=C:\jdk-24

Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button.

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-24 and you use the C shell, you will have to put the following into your .cshrc file.

setenv PATH /usr/local/jdk-24/bin:$PATH 
setenv JAVA_HOME /usr/local/jdk-24

Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE.

Popular Java Editors

To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −

  • Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.

  • Netbeans − It is a Java IDE that is open-source and free, which can be downloaded from www.netbeans.org/index.html.

  • Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.

jsoup Environment

Download the latest version of jsoup jar files.

At the time of writing this tutorial, we have copied them into C:\>passay folder.

OS Archive name
Windows passay-1.6.6.jar
Linux passay-1.6.6.jar
Mac passay-1.6.6.jar

Set CLASSPATH Variable

Set the CLASSPATH environment variable to point to the passay jar location. Assuming, you have stored passay and related jars in passay folder on various Operating Systems as follows.

OS Output
Windows Set the environment variable CLASSPATH to %CLASSPATH%;C:\passay\passay-1.6.6.jar;.;
Linux export CLASSPATH=$CLASSPATH:passay/passay-1.6.6.jar:.
Mac export CLASSPATH=$CLASSPATH:passay/passay-1.6.6.jar:.

Passay - Password Validation

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 - Validating a valid password against password policy

The below example shows the validation of a valid password against above policy using Passay library.

PassayDemo.java

package com.tutorialspoint;

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 PassayDemo {
   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

Compile and run the code to verify the result −

Password validated.

Example - Checking an invalid password against password policy

The below example shows the validation of an invalid password against password policy using Passay library.

PassayDemo.java

package com.tutorialspoint;

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 PassayDemo {
   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");        
      RuleResult result = validator.validate(password);
        
      if(result.isValid()){
         System.out.println("Password validated.");
      } else {
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Invalid Password: [Password must contain 1 or more digit characters., Password must contain 1 or more special characters.]

Passay - Customized Messages

Passay libary provides a MessageResolver API to override the default messages used by the validator. It can take the path to custom properties file and use the standard keys to override the required message.

Keys and Default Values

HISTORY_VIOLATION=Password matches one of %1$s previous passwords.
ILLEGAL_WORD=Password contains the dictionary word '%1$s'.
ILLEGAL_WORD_REVERSED=Password contains the reversed dictionary word '%1$s'.
ILLEGAL_DIGEST_WORD=Password contains a dictionary word.
ILLEGAL_DIGEST_WORD_REVERSED=Password contains a reversed dictionary word.
ILLEGAL_MATCH=Password matches the illegal pattern '%1$s'.
ALLOWED_MATCH=Password must match pattern '%1$s'.
ILLEGAL_CHAR=Password %2$s the illegal character '%1$s'.
ALLOWED_CHAR=Password %2$s the illegal character '%1$s'.
ILLEGAL_QWERTY_SEQUENCE=Password contains the illegal QWERTY sequence '%1$s'.
ILLEGAL_ALPHABETICAL_SEQUENCE=Password contains the illegal alphabetical sequence '%1$s'.
ILLEGAL_NUMERICAL_SEQUENCE=Password contains the illegal numerical sequence '%1$s'.
ILLEGAL_USERNAME=Password %2$s the user id '%1$s'.
ILLEGAL_USERNAME_REVERSED=Password %2$s the user id '%1$s' in reverse.
ILLEGAL_WHITESPACE=Password %2$s a whitespace character.
ILLEGAL_NUMBER_RANGE=Password %2$s the number '%1$s'.
ILLEGAL_REPEATED_CHARS=Password contains %3$s sequences of %1$s or more repeated characters, but only %2$s allowed: %4$s.
INSUFFICIENT_UPPERCASE=Password must contain %1$s or more uppercase characters.
INSUFFICIENT_LOWERCASE=Password must contain %1$s or more lowercase characters.
INSUFFICIENT_ALPHABETICAL=Password must contain %1$s or more alphabetical characters.
INSUFFICIENT_DIGIT=Password must contain %1$s or more digit characters.
INSUFFICIENT_SPECIAL=Password must contain %1$s or more special characters.
INSUFFICIENT_CHARACTERISTICS=Password matches %1$s of %3$s character rules, but %2$s are required.
INSUFFICIENT_COMPLEXITY=Password meets %2$s complexity rules, but %3$s are required.
INSUFFICIENT_COMPLEXITY_RULES=No rules have been configured for a password of length %1$s.
SOURCE_VIOLATION=Password cannot be the same as your %1$s password.
TOO_LONG=Password must be no more than %2$s characters in length.
TOO_SHORT=Password must be %1$s or more characters in length.
TOO_MANY_OCCURRENCES=Password contains %2$s occurrences of the character '%1$s', but at most %3$s are allowed.

Example - Custom Message on validation of Password

The below example shows the validation of a password and show a custom message using Passay library.

messages.properties

Create messages.properties with following content in the classpath.

INSUFFICIENT_UPPERCASE=Password missing at least %1$s uppercase characters.

PassayDemo.java

package com.tutorialspoint;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.passay.CharacterRule;
import org.passay.EnglishCharacterData;
import org.passay.LengthRule;
import org.passay.MessageResolver;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.PropertiesMessageResolver;
import org.passay.Rule;
import org.passay.RuleResult;
import org.passay.WhitespaceRule;

public class PassayDemo {
   public static void main(String[] args) throws FileNotFoundException, IOException {
      List<Rule> rules = new ArrayList<>();
      rules.add(new LengthRule(8, 16));
      rules.add(new WhitespaceRule());
      rules.add(new CharacterRule(EnglishCharacterData.UpperCase, 1));
      rules.add(new CharacterRule(EnglishCharacterData.LowerCase, 1));
      rules.add(new CharacterRule(EnglishCharacterData.Digit, 1));
      rules.add(new CharacterRule(EnglishCharacterData.Special, 1));

      Properties props = new Properties();
      props.load(new FileInputStream("messages.properties"));
      MessageResolver resolver = new PropertiesMessageResolver(props);

      PasswordValidator validator = new PasswordValidator(resolver, 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

Compile and run the code to verify the result −

Invalid Password: [Password missing at least 1 uppercase characters.]

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.

Syntax - Define a M of N Rule

// Define a M of N rule
CharacterCharacteristicsRule rule3 = new CharacterCharacteristicsRule();        

// Define M - Mandatory characters count
rule3.setNumberOfCharacteristics(3);        

Example - Validating a Password meeting at least three rule.

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

PassayDemo.java

package com.tutorialspoint;

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 PassayDemo {
   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();        
	  
	  // Define a M of N rule
      CharacterCharacteristicsRule rule3 = new CharacterCharacteristicsRule();        
      
	  // Define M - Mandatory characters count
      rule3.setNumberOfCharacteristics(3);        
      
	  // Define elements of N (upper, lower, digit, symbol)
	  //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

Compile and run the code to verify the result −

Password validated.

Example - Validating a Password not meeting at least three rule.

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

PassayDemo.java

package com.tutorialspoint;

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 PassayDemo {
   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();        
	  
	  // Define a M of N rule
      CharacterCharacteristicsRule rule3 = new CharacterCharacteristicsRule();        
      
	  // Define M - Mandatory characters count
      rule3.setNumberOfCharacteristics(3);        
      
	  // Define elements of N (upper, lower, digit, symbol)
	  //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("microsoft123");        
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      } else {
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Invalid Password: [Password must contain 1 or more uppercase characters., Password must contain 1 or more special characters., Password matches 2 of 4 character rules, but 3 are required.]

Passay - Password Generation

PasswordGenerator class helps in generating password using given policy. Consider the following policy:

  • Length of password should be 8 characters.

  • A password should contains each of the following: upper, lower, digit and a symbol.

Example - Generating Password using Rules array

The below example shows the generation of a password against above policy using Passay library.

PassayDemo.java

package com.tutorialspoint;

import org.passay.CharacterRule;
import org.passay.EnglishCharacterData;
import org.passay.PasswordGenerator;
import org.passay.Rule;

public class PassayDemo {
   public static void main(String[] args) {
	  Rule[] rules = new Rule[3];
	  rules[0] = new CharacterRule(EnglishCharacterData.Alphabetical);
	  rules[1] = new CharacterRule(EnglishCharacterData.Digit);
	  rules[2] = new CharacterRule(EnglishCharacterData.Special);

      PasswordGenerator passwordGenerator = new PasswordGenerator();
      String password = passwordGenerator.generatePassword(8, rules);
      System.out.println(password);
   }
}

Output

Compile and run the code to verify the result −

–·”yv2^±

Example - Generating Password using Rules List

The below example shows the generation of a password against above policy using Passay library.

PassayDemo.java

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

import org.passay.CharacterRule;
import org.passay.EnglishCharacterData;
import org.passay.PasswordGenerator;
import org.passay.Rule;

public class PassayDemo {
   public static void main(String[] args) {
	  List<Rule> rules = new ArrayList<>();
	  rules.add(new CharacterRule(EnglishCharacterData.Alphabetical));
	  rules.add(new CharacterRule(EnglishCharacterData.Digit));
	  rules.add(new CharacterRule(EnglishCharacterData.Special));

      PasswordGenerator passwordGenerator = new PasswordGenerator();
      String password = passwordGenerator.generatePassword(8, rules);
      System.out.println(password);
   }
}

Output

Compile and run the code to verify the result −

;d”9dv₶6

Passay - AllowedCharacterRule

AllowedCharacterRule class allows to specify the characters which a password can include.

Example - Validating Password for allowed characters

The below example shows validation of an invalid password for allowed characters

PassayDemo.java

package com.tutorialspoint;

import org.passay.AllowedCharacterRule;
import org.passay.LengthRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.Rule;
import org.passay.RuleResult;

public class PassayDemo {
   public static void main(String[] args) {
      //Rule: Password should contains only a, b and c       
      Rule rule1 = new AllowedCharacterRule(new char[] {'a', 'b', 'c'});
      //8 and 16 characters
      Rule rule2 = new LengthRule(8, 16);    

      PasswordValidator validator = new PasswordValidator(rule1, rule2);
      PasswordData password = new PasswordData("abcabcab1");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      } else {
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Invalid Password: [Password contains the illegal character '1'.]

Example - Validating a valid Password for allowed characters

The below example shows validation of an valid password for allowed characters

PassayDemo.java

package com.tutorialspoint;

import org.passay.AllowedCharacterRule;
import org.passay.LengthRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.Rule;
import org.passay.RuleResult;

public class PassayDemo {
   public static void main(String[] args) {
      //Rule: Password should contains only a, b and c       
      Rule rule1 = new AllowedCharacterRule(new char[] {'a', 'b', 'c'});
      //8 and 16 characters
      Rule rule2 = new LengthRule(8, 16);    

      PasswordValidator validator = new PasswordValidator(rule1, rule2);
      PasswordData password = new PasswordData("abcabcab");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      } else {
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Password validated.

Passay - AllowedRegexRule

AllowedRegexRule class allows to specify the regular pattern which a password should satisfy.

Example - Validating Password as per Regex pattern

The below example shows validation of an invalid password as per regex pattern

PassayDemo.java

package com.tutorialspoint;

import org.passay.AllowedRegexRule;
import org.passay.LengthRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.Rule;
import org.passay.RuleResult;

public class PassayDemo {
   public static void main(String[] args) {
      //Rule: Password should contains alphabets only
      Rule rule1 = new AllowedRegexRule("^[A-Za-z]+$");
      //8 and 16 characters
      Rule rule2 = new LengthRule(8, 16);    

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

Compile and run the code to verify the result −

Invalid Password: [Password must match pattern '^[A-Za-z]+$'.]

Example - Validating a valid Password as per Regex pattern

The below example shows validation of a valid password as per regex pattern

PassayDemo.java

package com.tutorialspoint;

import org.passay.AllowedRegexRule;
import org.passay.LengthRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.Rule;
import org.passay.RuleResult;

public class PassayDemo {
   public static void main(String[] args) {
      //Rule: Password should contains alphabets only
      Rule rule1 = new AllowedRegexRule("^[A-Za-z]+$");
      //8 and 16 characters
      Rule rule2 = new LengthRule(8, 16);    

      PasswordValidator validator = new PasswordValidator(rule1, rule2);
      PasswordData password = new PasswordData("microsoft");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      } else {
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Password validated.

Passay - CharacterRule

CharacterRule class helps in defining a set of characters and minimum no. of characters required in a password.

Example - Validating Password as per Character Rule

The below example shows validation of an invalid password as per set of characters.

PassayDemo.java

package com.tutorialspoint;

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 PassayDemo {
   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("Microsoft123");        
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      } else {
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Invalid Password: [Password must contain 1 or more special characters.]

Example - Validating a Valid Password as per Character Rule

The below example shows validation of a valid password as per set of characters.

PassayDemo.java

package com.tutorialspoint;

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 PassayDemo {
   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

Compile and run the code to verify the result −

Password validated.

Passay - LengthRule

LengthRule class helps in defining the minimum and maximum length of a password.

Example - Validating Password as per Length Rule

The below example shows validation of an invalid password as per length rules.

PassayDemo.java

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

import org.passay.LengthRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.Rule;
import org.passay.RuleResult;

public class PassayDemo {
   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));        
     
      PasswordValidator validator = new PasswordValidator(rules);        
      PasswordData password = new PasswordData("Micro");        
      RuleResult result = validator.validate(password);
        
      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Invalid Password: [Password must be 8 or more characters in length.]

Example - Validating a Valid Password as per Length Rule

The below example shows validation of a valid password as per length rules.

PassayDemo.java

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

import org.passay.LengthRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.Rule;
import org.passay.RuleResult;

public class PassayDemo {
   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));        
     
      PasswordValidator validator = new PasswordValidator(rules);        
      PasswordData password = new PasswordData("Microsoft");        
      RuleResult result = validator.validate(password);
        
      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Password validated.

Passay - CharacterCharacteristicsRule

CharacterCharacteristicsRule class helps in defining whether a password satisfy given N defined rules or not.

Example - Validating Password as per N defined Rule

The below example shows validation of an invalid password as per N defined rules.

PassayDemo.java

package com.tutorialspoint;

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 PassayDemo {
   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("microsoft123");        
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      } else {
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Invalid Password: [Password must contain 1 or more uppercase characters., Password must contain 1 or more special characters., Password matches 2 of 4 character rules, but 3 are required.]

Example - Validating a Valid Password as per N defined Rule

The below example shows validation of a valid password as per N defined rules.

PassayDemo.java

package com.tutorialspoint;

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 PassayDemo {
   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

Compile and run the code to verify the result −

Password validated.

Passay - LengthComplexityRule

LengthComplexityRule helps in defining the applicable rule on a password based on its length. Consider the following policy.

  • If length of password is in between 1 to 5 characters, only lower case alphabets are allowed.

  • If length of password is in between 6 to 8 characters, then only a, b and c are allowed.

Example - Validating Password as per Length Complexity Rule

The below example shows validation of an invalid password as per Length Complexity Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.AllowedCharacterRule;
import org.passay.CharacterRule;
import org.passay.EnglishCharacterData;
import org.passay.LengthComplexityRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;

public class PassayDemo {
   public static void main(String[] args) {
      LengthComplexityRule lengthComplexityRule = new LengthComplexityRule();
      //Rule: Password of 1 to 5 characters should contains lower case alphabets only
      lengthComplexityRule.addRules("[1,5]", 
         new CharacterRule(EnglishCharacterData.LowerCase, 5));
      //8 and 16 characters
      lengthComplexityRule.addRules("[6,8]", 
         new AllowedCharacterRule(new char[] { 'a', 'b', 'c' }));    
      PasswordValidator validator = new PasswordValidator(lengthComplexityRule);
      PasswordData password = new PasswordData("abcdef");
      RuleResult result = validator.validate(password);
      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Invalid Password: [Password contains the illegal character 'd'., Password contains the illegal character 'e'., Password contains the illegal character 'f'., Password meets 0 complexity rules, but 1 are required.]

Example - Validating a Valid Password as per Length Complexity Rule.

The below example shows validation of a valid password as per Length Complexity Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.AllowedCharacterRule;
import org.passay.CharacterRule;
import org.passay.EnglishCharacterData;
import org.passay.LengthComplexityRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;

public class PassayDemo {
   public static void main(String[] args) {
      LengthComplexityRule lengthComplexityRule = new LengthComplexityRule();
      //Rule: Password of 1 to 5 characters should contains lower case alphabets only
      lengthComplexityRule.addRules("[1,5]", 
         new CharacterRule(EnglishCharacterData.LowerCase, 5));
      //8 and 16 characters
      lengthComplexityRule.addRules("[6,8]", 
         new AllowedCharacterRule(new char[] { 'a', 'b', 'c' }));    
      PasswordValidator validator = new PasswordValidator(lengthComplexityRule);
      PasswordData password = new PasswordData("abcde");
      RuleResult result = validator.validate(password);
      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Password validated.

Passay - lllegalCharacterRule

lllegalCharacterRule helps allows to specify the characters which are not allowed in a password.

Example - Validating Password as per Illegal Character Rule

The below example shows validation of an invalid password as per Illegal Character Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.IllegalCharacterRule;
import org.passay.NumberRangeRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.passay.WhitespaceRule;

public class PassayDemo {
   public static void main(String[] args) {
      //Rule: Special characters like &, <, > are not allowed in a password 
      IllegalCharacterRule illegalCharacterRule 
         = new IllegalCharacterRule(new char[] {'&', '<', '>'});

      //Rule: 1 to 5 numbers are not allowed
      NumberRangeRule numberRangeRule = new NumberRangeRule(1, 5);

      //Rule: White spaces are not allowed
      WhitespaceRule whitespaceRule = new WhitespaceRule();

      PasswordValidator validator 
         = new PasswordValidator(illegalCharacterRule,numberRangeRule,whitespaceRule);
      PasswordData password = new PasswordData("abc&4d  ef6");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Invalid Password: [Password contains the illegal character '&'., Password contains the number '4'., Password contains a whitespace character.]

Example - Validating a Valid Password as per Illegal Characters Rule.

The below example shows validation of a valid password as per Illegal Characters Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.IllegalCharacterRule;
import org.passay.NumberRangeRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.passay.WhitespaceRule;

public class PassayDemo {
   public static void main(String[] args) {
      //Rule: Special characters like &, <, > are not allowed in a password 
      IllegalCharacterRule illegalCharacterRule 
         = new IllegalCharacterRule(new char[] {'&', '<', '>'});

      //Rule: 1 to 5 numbers are not allowed
      NumberRangeRule numberRangeRule = new NumberRangeRule(1, 5);

      //Rule: White spaces are not allowed
      WhitespaceRule whitespaceRule = new WhitespaceRule();

      PasswordValidator validator 
         = new PasswordValidator(illegalCharacterRule,numberRangeRule,whitespaceRule);
      PasswordData password = new PasswordData("abcdefg");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Password validated.

Passay - NumberRangeRule

NumberRangeRule helps allows to specify the characters which are not allowed in a password.

Example - Validating Password as per Number Range Rule

The below example shows validation of an invalid password as per Number Range Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.IllegalCharacterRule;
import org.passay.NumberRangeRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.passay.WhitespaceRule;

public class PassayDemo {
   public static void main(String[] args) {
      //Rule: Special characters like &, <, > are not allowed in a password 
      IllegalCharacterRule illegalCharacterRule 
         = new IllegalCharacterRule(new char[] {'&', '<', '>'});

      //Rule: 1 to 5 numbers are not allowed
      NumberRangeRule numberRangeRule = new NumberRangeRule(1, 5);

      //Rule: White spaces are not allowed
      WhitespaceRule whitespaceRule = new WhitespaceRule();

      PasswordValidator validator 
         = new PasswordValidator(illegalCharacterRule,numberRangeRule,whitespaceRule);
      PasswordData password = new PasswordData("abc&4d  ef6");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Invalid Password: [Password contains the illegal character '&'., Password contains the number '4'., Password contains a whitespace character.]

Example - Validating a Valid Password as per Number Range Rule.

The below example shows validation of a valid password as per Number Range Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.IllegalCharacterRule;
import org.passay.NumberRangeRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.passay.WhitespaceRule;

public class PassayDemo {
   public static void main(String[] args) {
      //Rule: Special characters like &, <, > are not allowed in a password 
      IllegalCharacterRule illegalCharacterRule 
         = new IllegalCharacterRule(new char[] {'&', '<', '>'});

      //Rule: 1 to 5 numbers are not allowed
      NumberRangeRule numberRangeRule = new NumberRangeRule(1, 5);

      //Rule: White spaces are not allowed
      WhitespaceRule whitespaceRule = new WhitespaceRule();

      PasswordValidator validator 
         = new PasswordValidator(illegalCharacterRule,numberRangeRule,whitespaceRule);
      PasswordData password = new PasswordData("abcdefg");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Password validated.

Passay - WhitespaceRule

WhitespaceRule helps allows to specify that the white spaces are not allowed in a password.

Example - Validating Password as per Whitespace Rule

The below example shows validation of an invalid password as per Whitespace Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.IllegalCharacterRule;
import org.passay.NumberRangeRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.passay.WhitespaceRule;

public class PassayDemo {
   public static void main(String[] args) {
      //Rule: Special characters like &, <, > are not allowed in a password 
      IllegalCharacterRule illegalCharacterRule 
         = new IllegalCharacterRule(new char[] {'&', '<', '>'});

      //Rule: 1 to 5 numbers are not allowed
      NumberRangeRule numberRangeRule = new NumberRangeRule(1, 5);

      //Rule: White spaces are not allowed
      WhitespaceRule whitespaceRule = new WhitespaceRule();

      PasswordValidator validator 
         = new PasswordValidator(illegalCharacterRule,numberRangeRule,whitespaceRule);
      PasswordData password = new PasswordData("abc&4d  ef6");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Invalid Password: [Password contains the illegal character '&'., Password contains the number '4'., Password contains a whitespace character.]

Example - Validating a Valid Password as per Whitespace Rule.

The below example shows validation of a valid password as per Whitespace Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.IllegalCharacterRule;
import org.passay.NumberRangeRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.passay.WhitespaceRule;

public class PassayDemo {
   public static void main(String[] args) {
      //Rule: Special characters like &, <, > are not allowed in a password 
      IllegalCharacterRule illegalCharacterRule 
         = new IllegalCharacterRule(new char[] {'&', '<', '>'});

      //Rule: 1 to 5 numbers are not allowed
      NumberRangeRule numberRangeRule = new NumberRangeRule(1, 5);

      //Rule: White spaces are not allowed
      WhitespaceRule whitespaceRule = new WhitespaceRule();

      PasswordValidator validator 
         = new PasswordValidator(illegalCharacterRule,numberRangeRule,whitespaceRule);
      PasswordData password = new PasswordData("abcdefg");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Password validated.

Passay - DictionaryRule

DictionaryRule helps allows to check if certain words are not specified as password.

Example - Validating Password as per Dictionary Rule

The below example shows validation of an invalid password as per Dictionary Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.DictionaryRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.passay.dictionary.ArrayWordList;
import org.passay.dictionary.WordListDictionary;

public class PassayDemo {
   public static void main(String[] args) {
      WordListDictionary wordListDictionary = new WordListDictionary(
         new ArrayWordList(new String[] { "password", "username" }));
      DictionaryRule dictionaryRule = new DictionaryRule(wordListDictionary);
      PasswordValidator validator = new PasswordValidator(dictionaryRule);
      PasswordData password = new PasswordData("password");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Invalid Password: [Password contains the dictionary word 'password'.]

Example - Validating a Valid Password as per Dictionary Rule.

The below example shows validation of a valid password as per Dictionary Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.DictionaryRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.passay.dictionary.ArrayWordList;
import org.passay.dictionary.WordListDictionary;

public class PassayDemo {
   public static void main(String[] args) {
      WordListDictionary wordListDictionary = new WordListDictionary(
         new ArrayWordList(new String[] { "password", "username" }));
      DictionaryRule dictionaryRule = new DictionaryRule(wordListDictionary);
      PasswordValidator validator = new PasswordValidator(dictionaryRule);
      PasswordData password = new PasswordData("password1323");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Password validated.

Passay - DictionarySubstringRule

DictionarySubstringRule helps allows to check if certain words are not part of a password.

Example - Validating Password as per Dictionary Substring Rule

The below example shows validation of an invalid password as per Dictionary Substring Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.DictionarySubstringRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.passay.dictionary.ArrayWordList;
import org.passay.dictionary.WordListDictionary;

public class PassayDemo {
   public static void main(String[] args) {
      WordListDictionary wordListDictionary = new WordListDictionary(
         new ArrayWordList(new String[] { "password", "username" }));
      DictionarySubstringRule dictionaryRule = new DictionarySubstringRule(wordListDictionary);
      PasswordValidator validator = new PasswordValidator(dictionaryRule);
      PasswordData password = new PasswordData("password@123");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Invalid Password: [Password contains the dictionary word 'password'.]

Example - Validating a Valid Password as per Dictionary Substring Rule.

The below example shows validation of a valid password as per Dictionary Substring Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.DictionarySubstringRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.passay.dictionary.ArrayWordList;
import org.passay.dictionary.WordListDictionary;

public class PassayDemo {
   public static void main(String[] args) {
      WordListDictionary wordListDictionary = new WordListDictionary(
         new ArrayWordList(new String[] { "password", "username" }));
      DictionarySubstringRule dictionaryRule = new DictionarySubstringRule(wordListDictionary);
      PasswordValidator validator = new PasswordValidator(dictionaryRule);
      PasswordData password = new PasswordData("Microsoft");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Password validated.

Passay - HistoryRule

HistoryRule allows to check if given password has not been in use in near past.

Example - Validating Password as per History Rule

The below example shows validation of an invalid password as per History Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.HistoryRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.passay.SourceRule;

public class PassayDemo {
   public static void main(String[] args) {
      SourceRule sourceRule = new SourceRule();
      HistoryRule historyRule = new HistoryRule();
      PasswordValidator validator = new PasswordValidator(sourceRule, historyRule);
      PasswordData password = new PasswordData("Microsoft@123");
      password.setPasswordReferences(
         new PasswordData.SourceReference("source", "password"), 
         new PasswordData.HistoricalReference("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

Compile and run the code to verify the result −

Invalid Password: [Password matches one of 1 previous passwords.]

Example - Validating a Valid Password as per History Rule.

The below example shows validation of a valid password as per History Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.HistoryRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import org.passay.SourceRule;

public class PassayDemo {
   public static void main(String[] args) {
      SourceRule sourceRule = new SourceRule();
      HistoryRule historyRule = new HistoryRule();
      PasswordValidator validator = new PasswordValidator(sourceRule, historyRule);
      PasswordData password = new PasswordData("Amazon@123");
      password.setPasswordReferences(
         new PasswordData.SourceReference("source", "password"), 
         new PasswordData.HistoricalReference("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

Compile and run the code to verify the result −

Password validated.

Passay - RepeatCharacterRegexRule

RepeatCharacterRegexRule allows to check if given password has repeated ascii characters.

Example - Validating Password as per Repeat Character Regex Rule

The below example shows validation of an invalid password as per Repeat Character Regex Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.LengthRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RepeatCharacterRegexRule;
import org.passay.Rule;
import org.passay.RuleResult;

public class PassayDemo {
   public static void main(String[] args) {
      //Rule: Password should not contain repeated entries
      Rule rule1 = new RepeatCharacterRegexRule(3);
      //8 and 16 characters
      Rule rule2 = new LengthRule(8, 16);    

      PasswordValidator validator = new PasswordValidator(rule1, rule2);
      PasswordData password = new PasswordData("aaefhehhhhh");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Invalid Password: [Password matches the illegal pattern 'hhh'.]

Example - Validating a Valid Password as per Repeat Character Regex Rule.

The below example shows validation of a valid password as per Repeat Character Regex Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.LengthRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RepeatCharacterRegexRule;
import org.passay.Rule;
import org.passay.RuleResult;

public class PassayDemo {
   public static void main(String[] args) {
      //Rule: Password should not contain repeated entries
      Rule rule1 = new RepeatCharacterRegexRule(3);
      //8 and 16 characters
      Rule rule2 = new LengthRule(8, 16);    

      PasswordValidator validator = new PasswordValidator(rule1, rule2);
      PasswordData password = new PasswordData("aaefhehh");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Password validated.

Passay - UsernameRule

UsernameRule ensures that password is not containing the username.

Example - Validating Password as per Username Rule

The below example shows validation of an invalid password as per Username Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.Rule;
import org.passay.RuleResult;
import org.passay.UsernameRule;

public class PassayDemo {
   public static void main(String[] args) {
      //Rule: Password should not contain user-name
      Rule rule = new UsernameRule();
      
      PasswordValidator validator = new PasswordValidator(rule);
      PasswordData password = new PasswordData("microsoft");
      password.setUsername("micro");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Invalid Password: [Password contains the user id 'micro'.]

Example - Validating a Valid Password as per Username Rule.

The below example shows validation of a valid password as per Username Rule.

PassayDemo.java

package com.tutorialspoint;

import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.Rule;
import org.passay.RuleResult;
import org.passay.UsernameRule;

public class PassayDemo {
   public static void main(String[] args) {
      //Rule: Password should not contain user-name
      Rule rule = new UsernameRule();
      
      PasswordValidator validator = new PasswordValidator(rule);
      PasswordData password = new PasswordData("amazon");
      password.setUsername("micro");
      RuleResult result = validator.validate(password);

      if(result.isValid()){
         System.out.println("Password validated.");
      }else{
         System.out.println("Invalid Password: " + validator.getMessages(result));            
      }
   }
}

Output

Compile and run the code to verify the result −

Password validated.
Advertisements