java 生成 6位密码,包含大小写字母和数字,三种类型都要有

要生成一个包含大小写字母和数字,并且三种类型都要有的6位密码,可以使用Java来实现。以下是一个示例代码,确保生成的密码符合要求:

示例代码

import java.security.SecureRandom;

public class PasswordGenerator {

    // 定义字符池
    private static final String LOWER_CASE = "abcdefghijklmnopqrstuvwxyz";
    private static final String UPPER_CASE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String DIGITS = "0123456789";
    private static final String ALL_CHARACTERS = LOWER_CASE + UPPER_CASE + DIGITS;

    public static void main(String[] args) {
        String password = generatePassword(6);
        System.out.println("Generated password: " + password);
    }

    public static String generatePassword(int length) {
        if (length < 6) {
            throw new IllegalArgumentException("Password length must be at least 6 characters.");
        }

        SecureRandom random = new SecureRandom();
        StringBuilder password = new StringBuilder(length);

        // 确保每种类型至少有一个字符
        password.append(LOWER_CASE.charAt(random.nextInt(LOWER_CASE.length())));
        password.append(UPPER_CASE.charAt(random.nextInt(UPPER_CASE.length())));
        password.append(DIGITS.charAt(random.nextInt(DIGITS.length())));

        // 填充剩余的字符
        for (int i = 3; i < length; i++) {
            password.append(ALL_CHARACTERS.charAt(random.nextInt(ALL_CHARACTERS.length())));
        }

        // 将密码打乱顺序
        return shuffleString(password.toString());
    }

    // 打乱字符串顺序
    private static String shuffleString(String input) {
        List<Character> characters = new ArrayList<>();
        for (char c : input.toCharArray()) {
            characters.add(c);
        }
        Collections.shuffle(characters);
        StringBuilder output = new StringBuilder(characters.size());
        for (char c : characters) {
            output.append(c);
        }
        return output.toString();
    }
}

代码说明

  1. 字符池定义

    • LOWER_CASE 包含小写字母。
    • UPPER_CASE 包含大写字母。
    • DIGITS 包含数字。
    • ALL_CHARACTERS 是以上三种字符池的组合。
  2. 密码生成逻辑

    • 确保每种类型至少有一个字符。
    • 使用 SecureRandom 生成随机字符。
    • 使用 StringBuilder 构建密码。
  3. 打乱字符串顺序

    • 将生成的密码字符打乱,以确保随机性。

生成示例

运行代码后,你将得到一个6位的随机密码,例如 aB3dE2。这个密码包含至少一个小写字母、一个大写字母和一个数字,并且所有字符顺序是随机的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值