In this post under Passay, I will show how to check whether the password is already used in another source.
Below is the complete main class for your reference.
Main class
1 package defaultPackage;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 import org.passay.PasswordData;
7 import org.passay.PasswordData.SourceReference;
8 import org.passay.PasswordValidator;
9 import org.passay.RuleResult;
10 import org.passay.SourceRule;
11
12 public class Example20 {
13 public static void main(String[] args) {
14 PasswordData.SourceReference sourceReference1 = new SourceReference("afajslf");
15 PasswordData.SourceReference sourceReference2 = new SourceReference("afafew");
16 PasswordData.SourceReference sourceReference3 = new SourceReference("jjjkj");
17 PasswordData.SourceReference sourceReference4 = new SourceReference("nxcvnx");
18
19 List<PasswordData.Reference> passwordSource = new ArrayList<>(0);
20 passwordSource.add(sourceReference1);
21 passwordSource.add(sourceReference2);
22 passwordSource.add(sourceReference3);
23 passwordSource.add(sourceReference4);
24
25 SourceRule sourceRule = new SourceRule();
26 PasswordValidator passwordValidator = new PasswordValidator(sourceRule);
27
28 PasswordData passwordData = new PasswordData("hello");
29 passwordData.setPasswordReferences(passwordSource);
30
31 RuleResult result = passwordValidator.validate(passwordData);
32 System.out.println(result.isValid());
33
34 passwordData = new PasswordData("nxcvnx");
35 passwordData.setPasswordReferences(passwordSource);
36
37 result = passwordValidator.validate(passwordData);
38 System.out.println(result.isValid());
39 }
40 }
In the above code, from line 14 to 17, I will create 4 instances of “PasswordData.SourceReference” class.
At line 19, I create a list named “passwordSource” and add these 4 instances in that list.
This list represents the passwords coming from another source.
At line 25, I create an instance of “SourceRule” class named “sourceRule”.
At line 26, I create an instance of “PasswordValidator” and pass “sourceRule” as constructor argument.
At line 28, I create a new password “hello” and store it in “PasswordData” instance.
At line 29, we set the list “passwordSource” to this instance of “PasswordData”.
At line 31, I call “validate” method available on “PasswordValidator” instance and pass “PasswordData” instance as an argument.
The validator will check the given password against the list of passwords and if present the password is invalid or else valid.
In this case, “hello” is not present in the password list, so it is valid.
We repeat the same process for another password “nxcvnx”.
This password is invalid as it is already present in the password list.
In this way we can check whether the password is already used in another source or not.