这是我第一次使用java.security.SecureRandom,我希望有人批评以下代码,以确保我正确地执行此操作。该代码应该生成任意长度的加密安全随机密码。任何意见都将不胜感激。
import java.util.*;
import java.security.SecureRandom;
public class PassGen{
private static final String VALID_PW_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+{}[]|:;<>?,./";
private static final int DEFAULT_PASSWORD_LENGTH = 12;
private static final Random RANDOM = new SecureRandom();
// main class
public static void main(String args[]) throws Exception {
// Set password length
int pwLength;
if (args.length < 1)
pwLength = DEFAULT_PASSWORD_LENGTH;
else
pwLength = Integer.parseInt(args[0]);
// generate password
String pw = "";
for (int i=0; i<pwLength; i++) {
int index = (int)(RANDOM.nextDouble()*VALID_PW_CHARS.length());
pw += VALID_PW_CHARS.substring(index, index+1);
}
System.out.println("pw = " + pw);
}
}
答案 0 :(得分:2)
使用StringBuilder
而不是反复连接字符串。此外,您应该使用string.charAt(index)
而不是使用子字符串表示单个字符:
import java.util.*;
import java.security.SecureRandom;
public class PassGen{
private static final String VALID_PW_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()-_=+{}[]|:;<>?,./";
private static final int DEFAULT_PASSWORD_LENGTH = 12;
private static final Random RANDOM = new SecureRandom();
// main class
public static void main(String args[]) throws Exception {
// Set password length
int pwLength;
if (args.length < 1)
pwLength = DEFAULT_PASSWORD_LENGTH;
else
pwLength = Integer.parseInt(args[0]);
StringBuilder pw = new StringBuilder();
// generate password
for (int i=0; i<pwLength; i++) {
int index = (int)(RANDOM.nextInt(VALID_PW_CHARS.length());
pw.append(VALID_PW_CHARS.charAt(index)));
}
System.out.println("pw = " + pw.toString());
}
}
此外,您正在生成double
并且不限制索引值。我做了一个有效字符数组长度的mod来解决这个问题。
答案 1 :(得分:2)
您可以使用org.apache.commons.lang.RandomStringUtils(http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/RandomStringUtils.html)使用char数组和java.security.SecureRandom生成密码:
public String generatePassword()
{
return RandomStringUtils.random(DEFAULT_PASSWORD_LENGTH, 0, VALID_PW_CHARS.length(), false,
false, VALID_PW_CHARS.toCharArray(), new SecureRandom());
}
在pom.xml中
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>