随机密码生成器java
时间: 2023-08-28 08:06:44 浏览: 66
可以使用Java的SecureRandom类生成随机密码,代码如下:
```java
import java.security.SecureRandom;
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_CHAR = "!@#$%&*()_+-=[]?";
private static final String PASSWORD_ALLOW_BASE = CHAR_LOWER + CHAR_UPPER + NUMBER + OTHER_CHAR;
private static SecureRandom random = new SecureRandom();
public static void main(String[] args) {
int length = 10;
// generate a random password
String password = generateRandomPassword(length);
System.out.println("Password: " + password);
}
public static String generateRandomPassword(int length) {
if (length < 1) {
throw new IllegalArgumentException("Invalid password length");
}
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int rndCharAt = random.nextInt(PASSWORD_ALLOW_BASE.length());
char rndChar = PASSWORD_ALLOW_BASE.charAt(rndCharAt);
sb.append(rndChar);
}
return sb.toString();
}
}
```
在上面的代码中,我们定义了一个包含小写字母、大写字母、数字和其他符号的字符集,然后使用SecureRandom类来生成随机字符并将其连接成密码字符串。可以通过调用generateRandomPassword方法来生成指定长度的随机密码。
阅读全文