How to Generate Random Alphanumeric Strings

How to generate a random alpha-numeric string

Algorithm

To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length.

Implementation

Here's some fairly simple and very flexible code for generating random identifiers. Read the information that follows for important application notes.

public class RandomString {

/**
* Generate a random string.
*/
public String nextString() {
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = symbols[random.nextInt(symbols.length)];
return new String(buf);
}

public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

public static final String lower = upper.toLowerCase(Locale.ROOT);

public static final String digits = "0123456789";

public static final String alphanum = upper + lower + digits;

private final Random random;

private final char[] symbols;

private final char[] buf;

public RandomString(int length, Random random, String symbols) {
if (length < 1) throw new IllegalArgumentException();
if (symbols.length() < 2) throw new IllegalArgumentException();
this.random = Objects.requireNonNull(random);
this.symbols = symbols.toCharArray();
this.buf = new char[length];
}

/**
* Create an alphanumeric string generator.
*/
public RandomString(int length, Random random) {
this(length, random, alphanum);
}

/**
* Create an alphanumeric strings from a secure generator.
*/
public RandomString(int length) {
this(length, new SecureRandom());
}

/**
* Create session identifiers.
*/
public RandomString() {
this(21);
}

}

Usage examples

Create an insecure generator for 8-character identifiers:

RandomString gen = new RandomString(8, ThreadLocalRandom.current());

Create a secure generator for session identifiers:

RandomString session = new RandomString();

Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols:

String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";
RandomString tickets = new RandomString(23, new SecureRandom(), easy);

Use as session identifiers

Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used.

There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand.

The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible.

Use as object identifiers

Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big.

Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission.

Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox." The probability of a collision, p, is approximately n2/(2qx), where n is the number of identifiers actually generated, q is the number of distinct symbols in the alphabet, and x is the length of the identifiers. This should be a very small number, like 2‑50 or less.

Working this out shows that the chance of collision among 500k 15-character identifiers is about 2‑52, which is probably less likely than undetected errors from cosmic rays, etc.

Comparison with UUIDs

According to their specification, UUIDs are not designed to be unpredictable, and should not be used as session identifiers.

UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters.

UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.

How can I generate random alphanumeric strings?

I heard LINQ is the new black, so here's my attempt using LINQ:

private static Random random = new Random();

public static string RandomString(int length)
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}

(Note: The use of the Random class makes this unsuitable for anything security related, such as creating passwords or tokens. Use the RNGCryptoServiceProvider class if you need a strong random number generator.)

How to generate a random alphanumeric string of a custom length in java?

Create a String of the characters which can be included in the string:

String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

Generate an integer using the Random class and use it to get a random character from the String.

Random random = new Random();
alphabet.charAt(random.nextInt(alphabet.length()));

Do this n times, where n is your custom length, and append the character to a String.

StringBuilder builder = new StringBuilder(n);
for (int i = 0; i < n; i++) {
builder.append(/* The generated character */);
}

Together, this could look like:

private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

public String generateString(int length) {
Random random = new Random();
StringBuilder builder = new StringBuilder(length);

for (int i = 0; i < length; i++) {
builder.append(ALPHABET.charAt(random.nextInt(ALPHABET.length())));
}

return builder.toString();
}

How do I create a random alpha-numeric string in C++?

Mehrdad Afshari's answer would do the trick, but I found it a bit too verbose for this simple task. Look-up tables can sometimes do wonders:

#include <ctime>
#include <iostream>
#include <unistd.h>

std::string gen_random(const int len) {
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
std::string tmp_s;
tmp_s.reserve(len);

for (int i = 0; i < len; ++i) {
tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)];
}

return tmp_s;
}

int main(int argc, char *argv[]) {
srand((unsigned)time(NULL) * getpid());
std::cout << gen_random(12) << "\n";
return 0;
}

Note that rand generates poor-quality random numbers.

Random alpha-numeric string in JavaScript?

If you only want to allow specific characters, you could also do it like this:

function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');

Here's a jsfiddle to demonstrate: http://jsfiddle.net/wSQBx/

Another way to do it could be to use a special string that tells the function what types of characters to use. You could do that like this:

function randomString(length, chars) {
var mask = '';
if (chars.indexOf('a') > -1) mask += 'abcdefghijklmnopqrstuvwxyz';
if (chars.indexOf('A') > -1) mask += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (chars.indexOf('#') > -1) mask += '0123456789';
if (chars.indexOf('!') > -1) mask += '~`!@#$%^&*()_+-={}[]:";\'<>?,./|\\';
var result = '';
for (var i = length; i > 0; --i) result += mask[Math.floor(Math.random() * mask.length)];
return result;
}

console.log(randomString(16, 'aA'));
console.log(randomString(32, '#aA'));
console.log(randomString(64, '#A!'));

Fiddle: http://jsfiddle.net/wSQBx/2/

Alternatively, to use the base36 method as described below you could do something like this:

function randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}

Generating Alphanumeric random string in Java

If you want to control the characterset and length take for example

public static String randomString(char[] characterSet, int length) {
Random random = new SecureRandom();
char[] result = new char[length];
for (int i = 0; i < result.length; i++) {
// picks a random index out of character set > random character
int randomCharIndex = random.nextInt(characterSet.length);
result[i] = characterSet[randomCharIndex];
}
return new String(result);
}

and combine with

char[] CHARSET_AZ_09 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();

to specify the characterset.

It's not based on StringBuilder since you know the length and don't need all the overhead.

It allocates a char[] array of the correct size, then fills each cell in that array with a randomly chosen character from the input array.

more example use here: http://ideone.com/xvIZcd

How to generate random alphanumeric string from a given string in C#?

Try this

static char[] alphaU = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
static char[] alphaL = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
static char[] number = "0123456789".ToCharArray();
static Random random = new Random();
static StringBuilder sb = new StringBuilder(100);

private static string GenerateRandomAlphanumericValue(string input)
{
sb.Clear();
for (int i = 0; i < input.Length; i++)
{
if (char.IsNumber(input[i]))
{
int index = random.Next(0, number.Length);
sb.Append(number[index]);
}
else if (char.IsUpper(input[i]))
{
int index = random.Next(0, alphaU.Length);
sb.Append(alphaU[index]);
}
else if (char.IsLower(input[i]))
{
int index = random.Next(0, alphaL.Length);
sb.Append(alphaL[index]);
}
else
{
sb.Append(input[i]);
}
}

return sb.ToString();
}

How to generate sequential alphanumeric string in Java starting with specific string

I'll assume you need 0000 to 000Z, then 0010, 0011, 0012 and so on. You would need to keep track of the current id you need to generate. Something like this:

public class SequentialString {

private static final String START = "CLV0";
private static final String ALPHANUMERIC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

public static void main(String[] args) {
int totalLength = 8;
int numberOfIds = 111;
int countRemainingSymbols = totalLength - START.length();
for (int i = 0; i < numberOfIds; i++) {
StringBuilder end = new StringBuilder();
int current = i;//depending on exact case, you would need to keep track of current
int remainder = current % ALPHANUMERIC.length();//the index of next character
do {
end.append(ALPHANUMERIC.charAt(remainder));
current /= ALPHANUMERIC.length();//update to check if we need to add more characters
remainder = current % ALPHANUMERIC.length();//update index, only used if more chars are needed
} while (current > 0);
int padCount = countRemainingSymbols - end.length();
StringBuilder result = new StringBuilder(START).append("-");//- is for easier debugging, remove it for your case
for (int j = 0; j < padCount; j++) {
result.append("0");
}
result.append(end.reverse());
System.out.println(result);
}
}
}

Basically, using current and length of ALPHANUMERIC to calculate next char index, then calculate if more characters are needed, keep looping until no more chars are needed. Note that i am reversing generated sequence(variable end in code) before appending it.

Also note that this solution is not limited to ZZZZ, it can keep generating the sequence even after that.

Is there a more efficient way to generate 40 million alphanumeric unique random strings in C#

One way to speed things up is to avoid LINQ. For example, take a look at these two implementations:

public static string LinqStuff(int length)
{
const string chars = "abcdefghijklmnpqrstuvwxyz0123456789";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}

public static string ManualStuff(int length)
{
const string chars = "abcdefghijklmnpqrstuvwxyz0123456789";
const int clength = 35;

var buffer = new char[length];
for(var i = 0; i < length; ++i)
{
buffer[i] = chars[random.Next(clength)];
}

return new string(buffer);
}

Running it through this:

private void TestThis(long iterations)
{
Console.WriteLine($"Running {iterations} iterations...");

var sw = new Stopwatch();
sw.Start();
for (long i = 0; i < iterations; ++i)
{
LinqStuff(20);
}
sw.Stop();
Console.WriteLine($"LINQ took {sw.ElapsedMilliseconds} ms.");

sw.Reset();
sw.Start();
for (long i = 0; i < iterations; ++i)
{
ManualStuff(20);
}
sw.Stop();
Console.WriteLine($"Manual took {sw.ElapsedMilliseconds} ms.");
}

With this:

TestThis(50_000_000);

Yielded these results:

LINQ took 28272 ms.
Manual took 9449 ms.

So by using LINQ, you increase the time it takes to generate strings by 3 times.

You could tweak this more and squeeze out a few more seconds, probably (for example, send in the same char[] buffer to each call)



Related Topics



Leave a reply



Submit