Passay 简明教程

Passay − Quick Guide

Passay − Overview

Passay 是一个基于 Java 的密码生成和验证库。它在验证/生成密码时提供全面的功能列表,并且具有高度的可配置性。

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 具有 3 个核心组件。

Passay API has 3 core components.

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

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

  3. 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−

  1. Positive match require that passwords satisfy a rule.

  2. Negative match reject passwords that satisfy a rule.

Features

以下是 Passay 库提供的部分功能。

Following are some of the features that Passay library provides.

  1. 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.

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

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

  4. convenient − Easy to use.

  5. Extensible − All Passay components are extensible.

  6. Supports Internalization − Passay components are internationalization ready.

Passay − Environment Setup

Setup Java

如果您仍然愿意为 Java 编程语言设置您的环境,则本节指导您如何在您的机器上下载并设置 Java。请按照下面提到的步骤设置环境。

If you are still willing to set up your environment for Java programming language, then this section guides you on how to download and set up Java on your machine. Please follow the steps mentioned below to set up the environment.

Java SE 可以从链接 Download Java 中免费获取。因此,您可以根据自己的操作系统下载版本。

Java SE is freely available from the link Download Java. So you download a version based on your operating system.

按照说明下载 Java 并运行 .exe 以在您的计算机上安装 Java。安装计算机上的 Java 后,您需要设置环境变量以指向正确的安装目录 −

Follow the instructions to download Java and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories −

Setting up the Path for Windows 2000/XP

我们假设您已将 Java 安装在 c:\Program Files\java\jdk 目录中 −

We are assuming that you have installed Java in c:\Program Files\java\jdk directory −

  1. Right-click on 'My Computer' and select 'Properties'.

  2. Click on the 'Environment variables' button under the 'Advanced' tab.

  3. Now, alter the 'Path' variable so that it also contains the path to the Java executable. Example, if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read 'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.

Setting up the Path for Windows 95/98/ME

我们假设您已将 Java 安装在 c:\Program Files\java\jdk 目录中 −

We are assuming that you have installed Java in c:\Program Files\java\jdk directory −

  1. Edit the 'C:\autoexec.bat' file and add the following line at the end − 'SET PATH=%PATH%;C:\Program Files\java\jdk\bin'

Setting up the Path for Linux, UNIX, Solaris, FreeBSD

环境变量 PATH 应设置为指向已安装 Java 二进制文件的位置。如果你在这方面遇到问题,请参阅 shell 文档。

Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.

例如,如果您用 bash 作为您的 shell,则您将向您 '.bashrc: export PATH=/path/to/java:$PATH' 的末尾添加以下行

Example, if you use bash as your shell, then you would add the following line to the end of your '.bashrc: export PATH=/path/to/java:$PATH'

要编写 Java 程序,您需要一个文本编辑器。市场中有许多高级集成开发环境可用。但目前,您可以考虑以下选项之一 −

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 −

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

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

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

Download Passay Archive

Maven Repository - 下载最新版本的Passay jar文件。在本教程中,已下载passay-1.6.1.jar并复制到C:\>passay文件夹。

Download the latest version of Passay jar file from Maven Repository - . In this tutorial, passay-1.6.1.jar is downloaded and copied into C:\> passay folder.

OS

Archive name

Windows

passay-1.6.1.jar

Linux

passay-1.6.1.jar

Mac

passay-1.6.1.jar

Set Passay Environment

PASSAY 环境变量设置为指向Passay jar存储于本地机器的基本目录位置。假设,我们已在Passay文件夹中提取了passay-1.6.1.jar,如下所示,适用于各种操作系统。

Set the PASSAY environment variable to point to the base directory location where Passay jar is stored on your machine. Assuming, we’ve extracted passay-1.6.1.jar in Passay folder on various Operating Systems as follows.

OS

Output

Windows

Set the environment variable PASSAY to C:\Passay

Linux

export PASSAY=/usr/local/Passay

Mac

export PASSAY=/Library/Passay

Set CLASSPATH Variable

CLASSPATH 环境变量设置为指向Passay jar位置。假设,您已在Passay文件夹中存储了passay-1.6.1.jar,如下所示,适用于各种操作系统。

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

OS

Output

Windows

Set the environment variable CLASSPATH to %CLASSPATH%;%Passay%\passay-1.6.1.jar;.;

Linux

export CLASSPATH=$CLASSPATH:$PASSAY/passay-1.6.1.jar:.

Mac

export CLASSPATH=$CLASSPATH:$PASSAY/passay-1.6.1.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:

  1. Length of password should be in between 8 to 16 characters.

  2. A password should not contain any whitespace.

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

Example

以下示例显示了使用 Passay 库根据上述策略对密码进行验证的过程。

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.

Passay − Customized Messages

Passay库提供了一个MessageResolver API,用于覆盖验证程序使用的默认消息。它可以获取自定义属性文件的路径,并使用标准 keys 覆盖所需消息。

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.

Example

以下示例显示了如何使用Passay库验证密码并显示自定义消息。

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

messages.properties

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

PassayExample.java

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 PassayExample {
   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("E:/Test/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

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

Passay − M of N rules

很多时候,密码策略要求强制遵守给定规则中的最低规则,例如密码必须满足至少 M 条规则中的 N 条规则。考虑以下策略。

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.

  1. Length of password should be in between 8 to 16 characters.

  2. A password should not contain any whitespace.

  3. A password should contains at least three of the following: upper, lower, digit or symbol.

Example

以下示例显示了使用 Passay 库根据上述策略对密码进行验证的过程。

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.

Passay − Password Generation

PasswordGenerator 有助于根据给定的策略生成密码。请考虑以下策略:

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

  1. Length of password should be 8 characters.

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

Example

以下示例显示了如何使用Passay库根据上述策略生成密码。

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

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

public class PassayExample {
   public static void main(String[] args) {
      CharacterRule alphabets = new CharacterRule(EnglishCharacterData.Alphabetical);
      CharacterRule digits = new CharacterRule(EnglishCharacterData.Digit);
      CharacterRule special = new CharacterRule(EnglishCharacterData.Special);

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

Output

?\DE~@c3

Passay - AllowedCharacterRule

AllowedCharacterRule 允许指定密码可以包含的字符。请考虑以下示例。

AllowedCharacterRule allows to specify the characters which a password can include. Consider the following example.

Example

以下示例显示了使用 Passay 库根据上述策略对密码进行验证的过程。

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

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

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

Passay − AllowedRegexRule

AllowedRegexRule 允许指定密码应满足的正则模式。请考虑以下示例。

AllowedRegexRule allows to specify the regular pattern which a password should satisfy. Consider the following example.

Example

以下示例显示了使用 Passay 库根据上述策略对密码进行验证的过程。

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

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

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

Passay − CharacterRule

CharacterRule 有助于定义密码中所需的一组字符及其最小数量。

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

Example

以下示例显示了使用 Passay 库根据上述策略对密码进行验证的过程。

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.

Passay − LengthRule

LengthRule 有助于定义密码的最小长度和最大长度。

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

Example

以下示例显示了使用 Passay 库根据上述策略对密码进行验证的过程。

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.

Passay − CharacterCharacteristicsRule

CharacterCharacteristicsRule 有助于定义密码是否满足给定的N个定义规则。

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

Example

以下示例显示了使用 Passay 库根据上述策略对密码进行验证的过程。

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.

Passay − LengthComplexityRule

LengthComplexityRule 有助于根据密码长度定义其适用的规则。请考虑以下策略。

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

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

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

Example

以下示例显示了使用 Passay 库根据上述策略对密码进行验证的过程。

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

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

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.]

Passay - IllegalCharacterRule

IllegalCharacterRule 允许指定密码中不允许使用的字符。请考虑以下示例。

IllegalCharacterRule allows to specify the characters which are not allowed in a password. Consider the following example.

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

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

Passay − NumberRangeRule

NumberRangeRule 允许指定密码中不允许使用的数字范围。考虑以下示例。

NumberRangeRule allows to specify the range of numbers which are not allowed in a password. Consider the following example.

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

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

Passay − WhitespaceRule

WhitespaceRule 允许指定密码中不允许使用空格。请考虑以下示例。

WhitespaceRule allows to specify that the white spaces are not allowed in a password. Consider the following example.

Example

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

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

Passay − DictionaryRule

DictionaryRule 允许检查是否未将某些单词指定为密码。考虑以下示例。

DictionaryRule allows to check if certain words are not specified as password. Consider the following example.

Example

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

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

Passay − DictionarySubstringRule

DictionarySubstringRule 允许检查密码中是否不包含某些单词。请考虑以下示例。

DictionarySubstringRule allows to check if certain words are not part of a password. Consider the following example.

Example

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

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

Passay − HistoryRule

HistoryRule 允许检查给定的密码是否在近期内未使用过。请考虑以下示例。

HistoryRule allows to check if given password has not been in use in near past. Consider the following example.

Example

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

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

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

Passay − RepeatCharacterRegexRule

RepeatCharacterRegexRule 允许检查给定的密码是否包含重复的 ASCII 字符。请考虑以下示例。

RepeatCharacterRegexRule allows to check if given password has repeated ascii characters. Consider the following example.

Example

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

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

Passay − UsernameRule

UsernameRule 可确保密码不包含用户名。请考虑以下示例。

UsernameRule ensures that password is not containing the username. Consider the following example.

Example

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

public class PassayExample {
   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

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