如何生成随机字符串(密码),该字符串应包含大写和小写字母,数字和特殊符号,长度为6 in java
我的代码如下:
package pw;
import java.security.SecureRandom;
import java.util.Random;
public class PasswordBuilder {
private static final Random RANDOM = new SecureRandom();
public static void main(String[] args) {
System.out.println(generateRandomPassword());
}
public static String generateRandomPassword() {
String letters = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ0123456789!@#$%^&*()_-+";
String pw = "";
for (int i = 0; i < 6; i++) {
int index = (int) (RANDOM.nextDouble() * letters.length());
pw += letters.substring(index, index + 1);
}
return pw;
}
}
答案 0 :(得分:0)
使用安全随机,您可以在字符串中决定所需的字符,数字和字母。
public class RandomGenerator {
private static SecureRandom prng;
private static final Logger LOG = LoggerFactory
.getLogger(AuthTokenGenerator.class);
static {
try {
// Initialize SecureRandom
prng = SecureRandom.getInstance("SHA1PRNG");
} catch (NoSuchAlgorithmException e) {
LOG.info("ERROR while intantiating Secure Random: " + prng);
}
}
/**
* @return
*/
public static String getToken() {
try {
LOG.info("About to Generate Token in getToken()");
String token;
// generate a random number
String randomNum = Integer.toString(prng.nextInt());
// get its digest
MessageDigest sha = MessageDigest.getInstance("SHA-1");
byte[] result = sha.digest(randomNum.getBytes());
token = hexEncode(result);
LOG.info("Token in getToken(): " + token);
return token;
} catch (NoSuchAlgorithmException ex) {
return null;
}
}
/**
* @param aInput
* @return
*/
private static String hexEncode(byte[] aInput) {
StringBuilder result = new StringBuilder();
char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
for (byte b : aInput) {
result.append(digits[(b & 0xf0) >> 4]);
result.append(digits[b & 0x0f]);
}
return result.toString();
}
}