我一直在寻找一种简单的Java算法来生成伪随机字母数字字符串。在我的情况下,它将被用作唯一的会话/密钥标识符,“很可能”在超过50万代的时间内是唯一的(我的需求实际上不需要更复杂的东西)。
理想情况下,我可以根据我的独特性需求指定长度。例如,生成的长度为12的字符串可能看起来像“AEYGF7K0DM1X”。
我一直在寻找一种简单的Java算法来生成伪随机字母数字字符串。在我的情况下,它将被用作唯一的会话/密钥标识符,“很可能”在超过50万代的时间内是唯一的(我的需求实际上不需要更复杂的东西)。
理想情况下,我可以根据我的独特性需求指定长度。例如,生成的长度为12的字符串可能看起来像“AEYGF7K0DM1X”。
当前回答
高效而简短。
/**
* Utility class for generating random Strings.
*/
public interface RandomUtil {
int DEF_COUNT = 20;
Random RANDOM = new SecureRandom();
/**
* Generate a password.
*
* @return the generated password
*/
static String generatePassword() {
return generate(true, true);
}
/**
* Generate an activation key.
*
* @return the generated activation key
*/
static String generateActivationKey() {
return generate(false, true);
}
/**
* Generate a reset key.
*
* @return the generated reset key
*/
static String generateResetKey() {
return generate(false, true);
}
static String generate(boolean letters, boolean numbers) {
int
start = ' ',
end = 'z' + 1,
count = DEF_COUNT,
gap = end - start;
StringBuilder builder = new StringBuilder(count);
while (count-- != 0) {
int codePoint = RANDOM.nextInt(gap) + start;
switch (getType(codePoint)) {
case UNASSIGNED:
case PRIVATE_USE:
case SURROGATE:
count++;
continue;
}
int numberOfChars = charCount(codePoint);
if (count == 0 && numberOfChars > 1) {
count++;
continue;
}
if (letters && isLetter(codePoint)
|| numbers && isDigit(codePoint)
|| !letters && !numbers) {
builder.appendCodePoint(codePoint);
if (numberOfChars == 2)
count--;
}
else
count++;
}
return builder.toString();
}
}
其他回答
您可以使用UUID类及其getLeastSignificantBits()消息来获取64位随机数据,然后将其转换为基数36的数字(即由0-9、a-Z组成的字符串):
Long.toString(Math.abs( UUID.randomUUID().getLeastSignificantBits(), 36));
这将产生一个长达13个字符的字符串。我们使用Math.abs()来确保没有负号潜入。
最佳随机字符串生成器方法
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;
}
}
Java 8中的另一种选择是:
static final Random random = new Random(); // Or SecureRandom
static final int startChar = (int) '!';
static final int endChar = (int) '~';
static String randomString(final int maxLength) {
final int length = random.nextInt(maxLength + 1);
return random.ints(length, startChar, endChar + 1)
.collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
.toString();
}
在一行中:
Long.toHexString(Double.doubleToLongBits(Math.random()));
来源:Java-生成随机字符串
public static String generateSessionKey(int length){
String alphabet =
new String("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"); // 9
int n = alphabet.length(); // 10
String result = new String();
Random r = new Random(); // 11
for (int i=0; i<length; i++) // 12
result = result + alphabet.charAt(r.nextInt(n)); //13
return result;
}