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