1
19
20 package com.liferay.util;
21
22 import com.liferay.portal.kernel.util.StringUtil;
23 import com.liferay.portal.kernel.util.Validator;
24
25
32 public class PwdGenerator {
33
34 public static String KEY1 = "0123456789";
35
36 public static String KEY2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
37
38 public static String KEY3 = "abcdefghijklmnopqrstuvwxyz";
39
40 public static String getPinNumber() {
41 return _getPassword(KEY1, 4, true);
42 }
43
44 public static String getPassword() {
45 return getPassword(8);
46 }
47
48 public static String getPassword(int length) {
49 return _getPassword(KEY1 + KEY2 + KEY3, length, true);
50 }
51
52 public static String getPassword(String key, int length) {
53 return getPassword(key, length, true);
54 }
55
56 public static String getPassword(
57 String key, int length, boolean useAllKeys) {
58
59 return _getPassword(key, length, useAllKeys);
60 }
61
62 private static String _getPassword(
63 String key, int length, boolean useAllKeys) {
64
65 StringBuilder sb = new StringBuilder();
66
67 for (int i = 0; i < length; i++) {
68 sb.append(key.charAt((int)(Math.random() * key.length())));
69 }
70
71 String password = sb.toString();
72
73 if (!useAllKeys) {
74 return password;
75 }
76
77 boolean invalidPassword = false;
78
79 if (key.contains(KEY1)) {
80 if (Validator.isNull(StringUtil.extractDigits(password))) {
81 invalidPassword = true;
82 }
83 }
84
85 if (key.contains(KEY2)) {
86 if (password.equals(password.toLowerCase())) {
87 invalidPassword = true;
88 }
89 }
90
91 if (key.contains(KEY3)) {
92 if (password.equals(password.toUpperCase())) {
93 invalidPassword = true;
94 }
95 }
96
97 if (invalidPassword) {
98 return _getPassword(key, length, useAllKeys);
99 }
100
101 return password;
102 }
103
104 }