这是我第一次使用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);
}
}
您可以使用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>
使用StringBuilder
,而不是一遍又一遍地串联字符串。另外,您应该使用string.charAt(index)
代替单个字符的子字符串: