用java生成写一段可以生成任意位数强密码的代码
时间: 2023-03-31 13:02:28 浏览: 156
您好,我可以回答这个问题。以下是一段可以生成任意位数强密码的 Java 代码:
```java
import java.security.SecureRandom;
import java.util.Random;
public class PasswordGenerator {
private static final String UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String LOWER = "abcdefghijklmnopqrstuvwxyz";
private static final String DIGITS = "0123456789";
private static final String PUNCTUATION = "!@#$%^&*()_+~`|}{[]\\:;?><,./-=";
private static final String SYMBOLS = UPPER + LOWER + DIGITS + PUNCTUATION;
private static SecureRandom random = new SecureRandom();
public static String generate(int length) {
if (length < 1) {
throw new IllegalArgumentException("Length must be at least 1.");
}
StringBuilder sb = new StringBuilder(length);
sb.append(randomChar(UPPER));
sb.append(randomChar(LOWER));
sb.append(randomChar(DIGITS));
sb.append(randomChar(PUNCTUATION));
for (int i = 4; i < length; i++) {
sb.append(randomChar(SYMBOLS));
}
return shuffle(sb.toString());
}
private static char randomChar(String str) {
int index = random.nextInt(str.length());
return str.charAt(index);
}
private static String shuffle(String str) {
char[] chars = str.toCharArray();
for (int i = chars.length - 1; i > ; i--) {
int index = random.nextInt(i + 1);
char temp = chars[index];
chars[index] = chars[i];
chars[i] = temp;
}
return new String(chars);
}
}
```
这段代码使用了安全随机数生成器和字符串操作来生成强密码。您可以调用 `PasswordGenerator.generate(length)` 方法来生成指定长度的密码。
阅读全文