|
| 1 | +import java.util.Random; |
| 2 | + |
| 3 | +public class PasswordUtil { |
| 4 | + |
| 5 | + public static boolean validate(String password) { |
| 6 | +// return password.matches("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20})"); |
| 7 | + return validate2(password); |
| 8 | + } |
| 9 | + |
| 10 | + public static boolean hasSymbol(String password) { |
| 11 | + return password.matches(".*[@#$%].*"); |
| 12 | + } |
| 13 | + |
| 14 | + public static boolean hasUppercase(String password) { |
| 15 | + return password.matches(".*[A-Z].*"); |
| 16 | + } |
| 17 | + |
| 18 | + public static boolean hasLowerCase(String password) { |
| 19 | + return password.matches(".*[a-z].*"); |
| 20 | + } |
| 21 | + |
| 22 | + public static boolean hasDigit(String password) { |
| 23 | + return password.matches(".*\\d.*"); |
| 24 | + } |
| 25 | + |
| 26 | + public static boolean validate2(String pass) { |
| 27 | + boolean flag = true; |
| 28 | + |
| 29 | + if (pass.length() < 8) { |
| 30 | + //Password must have more than 8 chars |
| 31 | + flag = false; |
| 32 | + } else if (!hasDigit(pass)) { |
| 33 | + //Password must contains digit |
| 34 | + flag = false; |
| 35 | + } else if (!hasSymbol(pass)) { |
| 36 | + //Password must contains symbol |
| 37 | + flag = false; |
| 38 | + } else if (!hasUppercase(pass)) { |
| 39 | + //Password must contains Upper case |
| 40 | + flag = false; |
| 41 | + } else if (!hasLowerCase(pass)) { |
| 42 | + //Password must contains Lower case |
| 43 | + flag = false; |
| 44 | + } |
| 45 | + |
| 46 | + return flag; |
| 47 | + } |
| 48 | + |
| 49 | + public static String generatePassword(int len) { |
| 50 | + Random rnd = new Random(); |
| 51 | + String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz@#$%&"; |
| 52 | + StringBuilder sb = new StringBuilder(len); |
| 53 | + for (int i = 0; i < len; i++) { |
| 54 | + sb.append(AB.charAt(rnd.nextInt(AB.length()))); |
| 55 | + } |
| 56 | + if(validate2(sb.toString())){ |
| 57 | + return sb.toString(); |
| 58 | + }else{ |
| 59 | + return generatePassword(12); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments