001
014
015 package com.liferay.util;
016
017 import com.liferay.portal.kernel.log.Log;
018 import com.liferay.portal.kernel.log.LogFactoryUtil;
019 import com.liferay.portal.kernel.util.StringUtil;
020 import com.liferay.portal.kernel.util.Validator;
021
022 import java.security.SecureRandom;
023
024
028 public class PwdGenerator {
029
030 public static final String KEY1 = "0123456789";
031
032 public static final String KEY2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
033
034 public static final String KEY3 = "abcdefghijklmnopqrstuvwxyz";
035
036 public static String getPassword() {
037 return _generate(KEY1 + KEY2 + KEY3, 8, true);
038 }
039
040 public static String getPassword(int length) {
041 return _generate(KEY1 + KEY2 + KEY3, length, true);
042 }
043
044 public static String getPassword(String key, int length) {
045 return _generate(key, length, true);
046 }
047
048 public static String getPassword(
049 String key, int length, boolean useAllKeys) {
050
051 return _generate(key, length, useAllKeys);
052 }
053
054 public static String getPinNumber() {
055 return _generate(KEY1, 4, false);
056 }
057
058 private static String _generate(
059 String key, int length, boolean useAllKeys) {
060
061 int keysCount = 0;
062
063 if (key.contains(KEY1)) {
064 keysCount++;
065 }
066
067 if (key.contains(KEY2)) {
068 keysCount++;
069 }
070
071 if (key.contains(KEY3)) {
072 keysCount++;
073 }
074
075 if (keysCount > length) {
076 if (_log.isWarnEnabled()) {
077 _log.warn("Length is too short");
078 }
079
080 length = keysCount;
081 }
082
083 StringBuilder sb = new StringBuilder(length);
084
085 for (int i = 0; i < length; i++) {
086 sb.append(key.charAt(_secureRandom.nextInt(key.length())));
087 }
088
089 String password = sb.toString();
090
091 if (!useAllKeys) {
092 return password;
093 }
094
095 boolean invalidPassword = false;
096
097 if (key.contains(KEY1)) {
098 if (Validator.isNull(StringUtil.extractDigits(password))) {
099 invalidPassword = true;
100 }
101 }
102
103 if (key.contains(KEY2)) {
104 if (password.equals(password.toLowerCase())) {
105 invalidPassword = true;
106 }
107 }
108
109 if (key.contains(KEY3)) {
110 if (password.equals(password.toUpperCase())) {
111 invalidPassword = true;
112 }
113 }
114
115 if (invalidPassword) {
116 return _generate(key, length, useAllKeys);
117 }
118
119 return password;
120 }
121
122 private static Log _log = LogFactoryUtil.getLog(PwdGenerator.class);
123
124 private static SecureRandom _secureRandom = new SecureRandom();;
125
126 }