java随机密码生成库
时间: 2024-10-24 19:05:45 浏览: 16
在Java中,生成随机密码通常会涉及到`java.util.Random`类或者`java.security.SecureRandom`类,以及一些字符串操作。以下是一个简单的例子,展示了如何使用这些工具创建一个包含大写字母、小写字母、数字和特殊字符的随机密码:
```java
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
public class RandomPasswordGenerator {
private static final String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz";
private static final String CHAR_UPPER = CHAR_LOWER.toUpperCase();
private static final String NUMBER = "0123456789";
private static final String OTHER_CHARACTERS = "!@#$%^&*()_+-=[]{}|;:,.<>?";
public static String generate(int length) {
SecureRandom random = new SecureRandom();
StringBuilder sb = new StringBuilder(length);
// 遍历每个字符种类并添加到密码中
for (int i = 0; i < length; i++) {
int index;
if (i % 4 == 0) { // 每四个位置换一种字符类型
switch (random.nextInt(4)) {
case 0:
index = random.nextInt(CHAR_LOWER.length());
break;
case 1:
index = random.nextInt(CHAR_UPPER.length());
break;
case 2:
index = random.nextInt(NUMBER.length());
break;
default:
index = random.nextInt(OTHER_CHARACTERS.length());
break;
}
} else {
index = random.nextInt(CHAR_LOWER.length());
}
sb.append(CHAR_LOWER.charAt(index)); // 使用选择的字符
}
// 返回生成的密码
return sb.toString();
}
public static void main(String[] args) {
System.out.println(generate(12)); // 输出长度为12的随机密码
}
}
```
阅读全文