001
014
015 package com.liferay.util;
016
017 import com.liferay.portal.kernel.util.StringUtil;
018 import com.liferay.portal.kernel.util.Validator;
019
020
024 public class PwdGenerator {
025
026 public static String KEY1 = "0123456789";
027
028 public static String KEY2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
029
030 public static String KEY3 = "abcdefghijklmnopqrstuvwxyz";
031
032 public static String getPinNumber() {
033 return _getPassword(KEY1, 4, true);
034 }
035
036 public static String getPassword() {
037 return getPassword(8);
038 }
039
040 public static String getPassword(int length) {
041 return _getPassword(KEY1 + KEY2 + KEY3, length, true);
042 }
043
044 public static String getPassword(String key, int length) {
045 return getPassword(key, length, true);
046 }
047
048 public static String getPassword(
049 String key, int length, boolean useAllKeys) {
050
051 return _getPassword(key, length, useAllKeys);
052 }
053
054 private static String _getPassword(
055 String key, int length, boolean useAllKeys) {
056
057 StringBuilder sb = new StringBuilder(length);
058
059 for (int i = 0; i < length; i++) {
060 sb.append(key.charAt((int)(Math.random() * key.length())));
061 }
062
063 String password = sb.toString();
064
065 if (!useAllKeys) {
066 return password;
067 }
068
069 boolean invalidPassword = false;
070
071 if (key.contains(KEY1)) {
072 if (Validator.isNull(StringUtil.extractDigits(password))) {
073 invalidPassword = true;
074 }
075 }
076
077 if (key.contains(KEY2)) {
078 if (password.equals(password.toLowerCase())) {
079 invalidPassword = true;
080 }
081 }
082
083 if (key.contains(KEY3)) {
084 if (password.equals(password.toUpperCase())) {
085 invalidPassword = true;
086 }
087 }
088
089 if (invalidPassword) {
090 return _getPassword(key, length, useAllKeys);
091 }
092
093 return password;
094 }
095
096 }