这是我第一次使用 java.security.SecureRandom,我希望有人批评以下代码以确保我正确执行此操作。该代码应该生成任意长度的加密安全随 secret 码。任何意见将不胜感激。
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>
关于java - 使用 java SecureRandom 类创建随 secret 码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29756660/