我一直在寻找一种简单的Java算法来生成伪随机字母数字字符串。在我的情况下,它将被用作唯一的会话/密钥标识符,“很可能”在超过50万代的时间内是唯一的(我的需求实际上不需要更复杂的东西)。
理想情况下,我可以根据我的独特性需求指定长度。例如,生成的长度为12的字符串可能看起来像“AEYGF7K0DM1X”。
我一直在寻找一种简单的Java算法来生成伪随机字母数字字符串。在我的情况下,它将被用作唯一的会话/密钥标识符,“很可能”在超过50万代的时间内是唯一的(我的需求实际上不需要更复杂的东西)。
理想情况下,我可以根据我的独特性需求指定长度。例如,生成的长度为12的字符串可能看起来像“AEYGF7K0DM1X”。
当前回答
您可以创建一个包含所有字母和数字的字符数组,然后可以从该字符数组中随机选择并创建自己的字符串密码。
char[] chars = new char[62]; // Sum of letters and numbers
int i = 0;
for(char c = 'a'; c <= 'z'; c++) { // For letters
chars[i++] = c;
}
for(char c = '0'; c <= '9';c++) { // For numbers
chars[i++] = c;
}
for(char c = 'A'; c <= 'Z';c++) { // For capital letters
chars[i++] = c;
}
int numberOfCodes = 0;
String code = "";
while (numberOfCodes < 1) { // Enter how much you want to generate at one time
int numChars = 8; // Enter how many digits you want in your password
for(i = 0; i < numChars; i++) {
char c = chars[(int)(Math.random() * chars.length)];
code = code + c;
}
System.out.println("Code is:" + code);
}
其他回答
public class Utils {
private final Random RANDOM = new SecureRandom();
private final String ALPHABET = "0123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
private String generateRandomString(int length) {
StringBuffer buffer = new StringBuffer(length);
for (int i = 0; i < length; i++) {
buffer.append(ALPHABET.charAt(RANDOM.nextInt(ALPHABET.length())));
}
return new String(buffer);
}
}
我不太喜欢这些关于“简单”解决方案的答案:S
我会选择简单的;),纯Java,一行(熵基于随机字符串长度和给定字符集):
public String randomString(int length, String characterSet) {
return IntStream.range(0, length).map(i -> new SecureRandom().nextInt(characterSet.length())).mapToObj(randomInt -> characterSet.substring(randomInt, randomInt + 1)).collect(Collectors.joining());
}
@Test
public void buildFiveRandomStrings() {
for (int q = 0; q < 5; q++) {
System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")); // The character set can basically be anything
}
}
或者(更易读的老方法)
public String randomString(int length, String characterSet) {
StringBuilder sb = new StringBuilder(); // Consider using StringBuffer if needed
for (int i = 0; i < length; i++) {
int randomInt = new SecureRandom().nextInt(characterSet.length());
sb.append(characterSet.substring(randomInt, randomInt + 1));
}
return sb.toString();
}
@Test
public void buildFiveRandomStrings() {
for (int q = 0; q < 5; q++) {
System.out.println(randomString(10, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")); // The character set can basically be anything
}
}
但另一方面,你也可以使用UUID,它具有相当好的熵:
UUID.randomUUID().toString().replace("-", "")
这里是Java语言:
import static java.lang.Math.round;
import static java.lang.Math.random;
import static java.lang.Math.pow;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import static org.apache.commons.lang.StringUtils.leftPad
public class RandomAlphaNum {
public static String gen(int length) {
StringBuffer sb = new StringBuffer();
for (int i = length; i > 0; i -= 12) {
int n = min(12, abs(i));
sb.append(leftPad(Long.toString(round(random() * pow(36, n)), 36), n, '0'));
}
return sb.toString();
}
}
下面是一个运行示例:
scala> RandomAlphaNum.gen(42)
res3: java.lang.String = uja6snx21bswf9t89s00bxssu8g6qlu16ffzqaxxoy
最佳随机字符串生成器方法
public class RandomStringGenerator{
private static int randomStringLength = 25 ;
private static boolean allowSpecialCharacters = true ;
private static String specialCharacters = "!@$%*-_+:";
private static boolean allowDuplicates = false ;
private static boolean isAlphanum = false;
private static boolean isNumeric = false;
private static boolean isAlpha = false;
private static final String alphabet = "abcdefghijklmnopqrstuvwxyz";
private static boolean mixCase = false;
private static final String capAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final String num = "0123456789";
public static String getRandomString() {
String returnVal = "";
int specialCharactersCount = 0;
int maxspecialCharacters = randomStringLength/4;
try {
StringBuffer values = buildList();
for (int inx = 0; inx < randomStringLength; inx++) {
int selChar = (int) (Math.random() * (values.length() - 1));
if (allowSpecialCharacters)
{
if (specialCharacters.indexOf("" + values.charAt(selChar)) > -1)
{
specialCharactersCount ++;
if (specialCharactersCount > maxspecialCharacters)
{
while (specialCharacters.indexOf("" + values.charAt(selChar)) != -1)
{
selChar = (int) (Math.random() * (values.length() - 1));
}
}
}
}
returnVal += values.charAt(selChar);
if (!allowDuplicates) {
values.deleteCharAt(selChar);
}
}
} catch (Exception e) {
returnVal = "Error While Processing Values";
}
return returnVal;
}
private static StringBuffer buildList() {
StringBuffer list = new StringBuffer(0);
if (isNumeric || isAlphanum) {
list.append(num);
}
if (isAlpha || isAlphanum) {
list.append(alphabet);
if (mixCase) {
list.append(capAlpha);
}
}
if (allowSpecialCharacters)
{
list.append(specialCharacters);
}
int currLen = list.length();
String returnVal = "";
for (int inx = 0; inx < currLen; inx++) {
int selChar = (int) (Math.random() * (list.length() - 1));
returnVal += list.charAt(selChar);
list.deleteCharAt(selChar);
}
list = new StringBuffer(returnVal);
return list;
}
}
public static String randomSeriesForThreeCharacter() {
Random r = new Random();
String value = "";
char random_Char ;
for(int i=0; i<10; i++)
{
random_Char = (char) (48 + r.nextInt(74));
value = value + random_char;
}
return value;
}