我一直在寻找一种简单的Java算法来生成伪随机字母数字字符串。在我的情况下,它将被用作唯一的会话/密钥标识符,“很可能”在超过50万代的时间内是唯一的(我的需求实际上不需要更复杂的东西)。
理想情况下,我可以根据我的独特性需求指定长度。例如,生成的长度为12的字符串可能看起来像“AEYGF7K0DM1X”。
我一直在寻找一种简单的Java算法来生成伪随机字母数字字符串。在我的情况下,它将被用作唯一的会话/密钥标识符,“很可能”在超过50万代的时间内是唯一的(我的需求实际上不需要更复杂的东西)。
理想情况下,我可以根据我的独特性需求指定长度。例如,生成的长度为12的字符串可能看起来像“AEYGF7K0DM1X”。
当前回答
最佳随机字符串生成器方法
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 class AlphaNumericGenerator {
public static void main(String[] args) {
java.util.Random r = new java.util.Random();
int i = 1, n = 0;
char c;
String str = "";
for (int t = 0; t < 3; t++) {
while (true) {
i = r.nextInt(10);
if (i > 5 && i < 10) {
if (i == 9) {
i = 90;
n = 90;
break;
}
if (i != 90) {
n = i * 10 + r.nextInt(10);
while (n < 65) {
n = i * 10 + r.nextInt(10);
}
}
break;
}
}
c = (char)n;
str = String.valueOf(c) + str;
}
while(true){
i = r.nextInt(10000000);
if(i > 999999)
break;
}
str = str + i;
System.out.println(str);
}
}
这是算盘常用的一行:
String.valueOf(CharStream.random('0', 'z').filter(c -> N.isLetterOrDigit(c)).limit(12).toArray())
随机并不意味着它必须是唯一的。要获取唯一字符串,请使用:
N.uuid() // E.g.: "e812e749-cf4c-4959-8ee1-57829a69a80f". length is 36.
N.guid() // E.g.: "0678ce04e18945559ba82ddeccaabfcd". length is 32 without '-'
您提到“简单”,但如果其他人正在寻找符合更严格安全要求的产品,您可能需要看看jpwgen。jpwgen在Unix中以pwgen为模型,非常可配置。
给定一些字符(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));
}
}
在沙盒上试试另请参阅其他语言实现随机字符串生成器
我使用的是一个非常简单的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));
}