HaveIBeenPwnedRule example

In this post under Passay, I will show with example, the purpose of “HaveIBeenPwnedRule” rule class.

There is website “haveibeenpwned.com” that contains a list of real world passwords that were previously used and exposed as part of data breaches.

You can make sure that the password entered by the user or the password generated by Passay framework is not present in that database with the help of this rule class.

Below is the main class that shows how to use it.

Main class

1  package defaultPackage;
2  
3  import java.util.Scanner;
4  
5  import org.passay.HaveIBeenPwnedRule;
6  import org.passay.PasswordData;
7  import org.passay.PasswordValidator;
8  import org.passay.Rule;
9  import org.passay.RuleResult;
10 
11 public class Example9 {
12     public static void main(String[] args) {
13         Rule haveIBeenPwnedRule = new HaveIBeenPwnedRule("appName");
14         PasswordValidator passwordValidator = new PasswordValidator(haveIBeenPwnedRule);
15         
16         Scanner scanner = new Scanner(System.in);
17         System.out.println("First test");
18         System.out.println("Enter password");
19         String data = scanner.next();
20         PasswordData passwordData = new PasswordData(data);
21         RuleResult ruleResult = passwordValidator.validate(passwordData);
22         System.out.println("Result of password validation: " + ruleResult.isValid());
23         System.out.println("--------------------------------------");
24         
25         System.out.println("Second test");
26         System.out.println("Enter password");
27         data = scanner.next();
28         passwordData = new PasswordData(data);
29         ruleResult = passwordValidator.validate(passwordData);
30         System.out.println("Result of password validation: " + ruleResult.isValid());
31         System.out.println("--------------------------------------");
32     }
33 }

In the above code, at line 13, I create an instance of “HaveIBeenPwnedRule” rule class and pass the application name as a constructor argument.

At line 14, I create an instance of “PasswordValidator” class and pass instance created at 13 as an argument to its constructor.

Then I ask two inputs from the user and validate it against “haveibeenpwned.com” database.

In this way we can use “HaveIBeenPwnedRule” rule class.

Below is the output

Output

First test
Enter password
password
Result of password validation: false
--------------------------------------
Second test
Enter password
pa@&183042
Result of password validation: true
--------------------------------------

Leave a comment