package com.payegis.thunder.webapp.admin.util;
import java.util.Random;
public class RandomPasswordUtil {
/**
* 大寫字母、小寫字母、數字、特殊字符彙總
* @return
*/
public static char[] getChar() {
char[] passwordLit = new char[67];
char fword = 'A';
char mword = 'a';
char bword = '0';
for (int i = 0; i < 62; i++) {
if (i < 26) {
passwordLit[i] = fword;
fword++;
} else if (i < 52) {
passwordLit[i] = mword;
mword++;
} else {
passwordLit[i] = bword;
bword++;
}
}
passwordLit[62] = '!';
passwordLit[63] = '@';
passwordLit[64] = '#';
passwordLit[65] = '$';
passwordLit[66] = '&';
return passwordLit;
}
/**
* 生成隨機密碼,密碼規則符合:大寫字母、小寫字母、數字、特殊字符應選三種或以上
* @param length
* @return
*/
public static String getRandomPwdByCondition(int length) {
char[] r = getChar();
while (true) {
String randomPwd = getRandomPwd(r, length);
int count = 0;
if (randomPwd.matches(".*[a-z]{1,}.*")){
++count;
}
if (randomPwd.matches(".*[A-Z]{1,}.*")){
++count;
}
if (randomPwd.matches(".*\\d{1,}.*")){
++count;
}
if (randomPwd.matches(".*[!@#$&]{1,}.*")){
++count;
}
if (count >= 3){
return randomPwd;
}
}
}
public static String getRandomPwd(char[] r, int length) {
Random rr = new Random();
char[] pw = new char[length];
for (int i = 0; i < pw.length; i++) {
int num = rr.nextInt(67);
pw[i] = r[num];
}
return String.valueOf(pw);
}
public static String getRandomPwd(int length) {
char[] r = getChar();
Random rr = new Random();
char[] pw = new char[length];
for (int i = 0; i < pw.length; i++) {
int num = rr.nextInt(67);
pw[i] = r[num];
}
return String.valueOf(pw);
}
public static void main(String[] args) {
System.out.println(getRandomPwdByCondition(8));
}
}
生成隨機密碼,密碼規則符合:大寫字母、小寫字母、數字、特殊字符應選三種或以上
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.