欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

密码随机生成器

程序员文章站 2024-03-14 14:28:52
...

本代码密码复杂度8-25位,特殊字符、数字、字母大小写全都支持,可以直接cp使用

public class PasswordGenerator {

    private static final char[] CHARR = "[email protected]#$%&*".toCharArray();
    private static final String PASSWORD_REGEX = "^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![[email protected]#$^&*=?','+'。'-'/]+$)(?![a-z0-9]+$)(?![[email protected]#$^&*=?','+'。'-'/]+$)(?![[email protected]#$^&*=?','+'。'-'/]+$)[[email protected]#$^&*=?','+'。'-'/]{8,20}$";
    private static final Pattern PASSWORD_PATTERN = Pattern.compile(PASSWORD_REGEX);

    public static String generatePassword(int length) {
        length = length < 8 ? 8 : length;
        length = length > 25 ? 25 : length;
        String result = getRandomPassword(length);
        Matcher m = PASSWORD_PATTERN.matcher(result);
        if (m.matches()) {
            return result;
        }
        return generatePassword(length);
    }

    private static String getRandomPassword(int length) {
        StringBuilder sb = new StringBuilder();
        ThreadLocalRandom r = ThreadLocalRandom.current();
        for (int x = 0; x < length; ++x) {
            sb.append(CHARR[r.nextInt(CHARR.length)]);
        }
        return sb.toString();
    }
}