This is my first experience with java.security.SecureRandom and I'd like someone to critique the follow code to ensure I'm doing this correctly. The code is supposed to generate a cryptographically secure random password of arbitrary length. Any input would be appreciated.
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);
}
}
You can use org.apache.commons.lang.RandomStringUtils ( http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/RandomStringUtils.html ) to generate password using char array and 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());
}
In pom.xml
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
Use StringBuilder
instead of concatenating strings over and over. Also you should look at using string.charAt(index)
instead of using substring for single chars:
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 = RANDOM.nextInt(VALID_PW_CHARS.length());
pw.append(VALID_PW_CHARS.charAt(index)));
}
System.out.println("pw = " + pw.toString());
}
}
Also you are generating double
s and not restricting the index value. I did a mod of the length of the valid chars array to fix this problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.