package com.doumee.core.utils;
|
|
import com.doumee.core.constants.ResponseStatus;
|
import com.doumee.core.exception.BusinessException;
|
|
import java.security.SecureRandom;
|
import java.util.HashSet;
|
import java.util.Set;
|
|
/**
|
* Created by IntelliJ IDEA.
|
*
|
* @Author : Rk
|
* @create 2025/10/27 16:23
|
*/
|
public class PasswordGenerator {
|
|
private static final String LOWER = "abcdefghijklmnopqrstuvwxyz";
|
private static final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
private static final String DIGITS = "0123456789";
|
private static final String SYMBOLS = "!@#$%^&*()_+-=[]{};':|,.<>/?";
|
private static final String PASSWORD_CHARS = LOWER + UPPER + DIGITS + SYMBOLS;
|
private static final int PASSWORD_LENGTH = 8; // 你可以根据需要调整密码长度
|
|
public static void getPasswordTypeCount(String password){
|
Set<Integer> typeCount = new HashSet<>(4);
|
for (int i = 0; i < password.length(); i++) {
|
String key = password.substring(0,i);
|
if(LOWER.indexOf(key)>=Constants.ZERO){
|
typeCount.add(Constants.ZERO);
|
}else if(UPPER.indexOf(key)>=Constants.ZERO){
|
typeCount.add(Constants.ONE);
|
}else if(DIGITS.indexOf(key)>=Constants.ZERO){
|
typeCount.add(Constants.TWO);
|
}else if(SYMBOLS.indexOf(key)>=Constants.ZERO){
|
typeCount.add(Constants.THREE);
|
}else{
|
throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"请使用合法的密码内容");
|
}
|
}
|
if(typeCount.size()<Constants.THREE||password.length()<8){
|
throw new BusinessException(ResponseStatus.NOT_ALLOWED.getCode(),"密码至少包括数字、大写字母、小写字母、特殊字符中的三种字符,且至少8位数");
|
}
|
}
|
|
|
|
public static String generatePassword() {
|
SecureRandom random = new SecureRandom();
|
StringBuilder password = new StringBuilder(PASSWORD_LENGTH);
|
Set<Character> usedChars = new HashSet<>();
|
|
// while (password.length() < PASSWORD_LENGTH) {
|
// int index = random.nextInt(PASSWORD_CHARS.length());
|
// char randomChar = PASSWORD_CHARS.charAt(index);
|
// // 确保每种类型的字符至少出现一次
|
// if (usedChars.add(randomChar)) {
|
// password.append(randomChar);
|
// }
|
// }
|
// 如果需要确保每种类型都至少出现一次,可以注释掉上面的循环,使用下面的代码:
|
for (int i = 0; i < PASSWORD_LENGTH; i++) {
|
int type = random.nextInt(4); // 0=lower, 1=upper, 2=digit, 3=symbol
|
String charSet;
|
switch (type) {
|
case 0: charSet = LOWER; break;
|
case 1: charSet = UPPER; break;
|
case 2: charSet = DIGITS; break;
|
default: charSet = SYMBOLS; break;
|
}
|
int index = random.nextInt(charSet.length());
|
password.append(charSet.charAt(index));
|
}
|
// Shuffle the string to avoid predictable patterns (optional)
|
password.toString().chars()
|
.mapToObj(c -> (char) c)
|
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
|
.toString(); // This line is a no-op, but it's here to show the method call for completeness.
|
return password.toString();
|
}
|
|
public static void main(String[] args) {
|
System.out.println("Generated Password: " + generatePassword());
|
}
|
}
|