我一直在寻找一种简单的Java算法来生成伪随机字母数字字符串。在我的情况下,它将被用作唯一的会话/密钥标识符,“很可能”在超过50万代的时间内是唯一的(我的需求实际上不需要更复杂的东西)。
理想情况下,我可以根据我的独特性需求指定长度。例如,生成的长度为12的字符串可能看起来像“AEYGF7K0DM1X”。
我一直在寻找一种简单的Java算法来生成伪随机字母数字字符串。在我的情况下,它将被用作唯一的会话/密钥标识符,“很可能”在超过50万代的时间内是唯一的(我的需求实际上不需要更复杂的东西)。
理想情况下,我可以根据我的独特性需求指定长度。例如,生成的长度为12的字符串可能看起来像“AEYGF7K0DM1X”。
当前回答
如果您愿意使用Apache类,可以使用org.Apache.mons.text.RandomStringGenerator(Apache commons文本)。
例子:
RandomStringGenerator randomStringGenerator =
new RandomStringGenerator.Builder()
.withinRange('0', 'z')
.filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)
.build();
randomStringGenerator.generate(12); // toUpperCase() if you want
自Apache Commons Lang 3.6以来,RandomStringUtils已被弃用。
其他回答
我使用的是一个非常简单的Java8解决方案。只需根据您的需求进行定制。
...
import java.security.SecureRandom;
...
//Generate a random String of length between 10 to 20.
//Length is also randomly generated here.
SecureRandom random = new SecureRandom();
String sampleSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
int stringLength = random.ints(1, 10, 21).mapToObj(x -> x).reduce((a, b) -> a).get();
String randomString = random.ints(stringLength, 0, sampleSet.length() - 1)
.mapToObj(x -> sampleSet.charAt(x))
.collect(Collector
.of(StringBuilder::new, StringBuilder::append,
StringBuilder::append, StringBuilder::toString));
我们可以使用它生成如下的字母数字随机字符串(返回的字符串将强制包含一些非数字字符以及一些数字字符):
public String generateRandomString() {
String sampleSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_";
String sampleSetNumeric = "0123456789";
String randomString = getRandomString(sampleSet, 10, 21);
String randomStringNumeric = getRandomString(sampleSetNumeric, 10, 21);
randomString = randomString + randomStringNumeric;
//Convert String to List<Character>
List<Character> list = randomString.chars()
.mapToObj(x -> (char)x)
.collect(Collectors.toList());
Collections.shuffle(list);
//This is needed to force a non-numeric character as the first String
//Skip this for() if you don't need this logic
for(;;) {
if(Character.isDigit(list.get(0))) Collections.shuffle(list);
else break;
}
//Convert List<Character> to String
randomString = list.stream()
.map(String::valueOf)
.collect(Collectors.joining());
return randomString;
}
//Generate a random number between the lower bound (inclusive) and upper bound (exclusive)
private int getRandomLength(int min, int max) {
SecureRandom random = new SecureRandom();
return random.ints(1, min, max).mapToObj(x -> x).reduce((a, b) -> a).get();
}
//Generate a random String from the given sample string, having a random length between the lower bound (inclusive) and upper bound (exclusive)
private String getRandomString(String sampleSet, int min, int max) {
SecureRandom random = new SecureRandom();
return random.ints(getRandomLength(min, max), 0, sampleSet.length() - 1)
.mapToObj(x -> sampleSet.charAt(x))
.collect(Collector
.of(StringBuilder::new, StringBuilder::append,
StringBuilder::append, StringBuilder::toString));
}
我正在使用Apache Commons的库生成一个字母数字字符串:
import org.apache.commons.lang3.RandomStringUtils;
String keyLength = 20;
RandomStringUtils.randomAlphanumeric(keylength);
它又快又简单!
我找到了生成随机十六进制编码字符串的解决方案。所提供的单元测试似乎符合我的主要用例。虽然,它比提供的一些其他答案稍微复杂一些。
/**
* Generate a random hex encoded string token of the specified length
*
* @param length
* @return random hex string
*/
public static synchronized String generateUniqueToken(Integer length){
byte random[] = new byte[length];
Random randomGenerator = new Random();
StringBuffer buffer = new StringBuffer();
randomGenerator.nextBytes(random);
for (int j = 0; j < random.length; j++) {
byte b1 = (byte) ((random[j] & 0xf0) >> 4);
byte b2 = (byte) (random[j] & 0x0f);
if (b1 < 10)
buffer.append((char) ('0' + b1));
else
buffer.append((char) ('A' + (b1 - 10)));
if (b2 < 10)
buffer.append((char) ('0' + b2));
else
buffer.append((char) ('A' + (b2 - 10)));
}
return (buffer.toString());
}
@Test
public void testGenerateUniqueToken(){
Set set = new HashSet();
String token = null;
int size = 16;
/* Seems like we should be able to generate 500K tokens
* without a duplicate
*/
for (int i=0; i<500000; i++){
token = Utility.generateUniqueToken(size);
if (token.length() != size * 2){
fail("Incorrect length");
} else if (set.contains(token)) {
fail("Duplicate token generated");
} else{
set.add(token);
}
}
}
我不太喜欢这些关于“简单”解决方案的答案: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("-", "")
给定一些字符(AllCharacters),您可以随机选择字符串中的一个字符。然后使用for循环重复获取随机字符。
public class MyProgram {
static String getRandomString(int size) {
String AllCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder sb = new StringBuilder(size);
int length = AllCharacters.length();
for (int i = 0; i < size; i++) {
sb.append(AllCharacters.charAt((int)(length * Math.random())));
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(MyProgram.getRandomString(30));
}
}
在沙盒上试试另请参阅其他语言实现随机字符串生成器