How to Generate a Random, Unique, Alphanumeric String

How to generate a random, unique, alphanumeric string?

Security Notice: This solution should not be used in situations where the quality of your randomness can affect the security of an application. In particular, rand() and uniqid() are not cryptographically secure random number generators. See Scott's answer for a secure alternative.

If you do not need it to be absolutely unique over time:

md5(uniqid(rand(), true))

Otherwise (given you have already determined a unique login for your user):

md5(uniqid($your_user_login, true))

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 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.

Random unique alpha numeric string in java

Apache common lang utils is a great library for creating random numbers and many more useful stuff.

You can create a random string with letters and numbers as follows.

1 Get the dependency.
In gradle it is -

compile group: 'org.apache.commons', name: 'commons-lang3'

2 import randomutils

import org.apache.commons.lang3.RandomStringUtils;

3 Generate random string of size 8 with letters = true and numbers = true

RandomStringUtils.random(8, true, true)

Create unique plus random alphanumeric string

as mentioned here , uniqid() can create the same id many times:

<?php
for($i=0;$i<20;$i++) {
echo uniqid(), PHP_EOL;
}

/** Example of Output:

5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c0ce
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6
5819f3ad1c4b6 */

i suggest to use the function that he created instead of using uniqid().

<?php
function uniqidReal($lenght = 13) {
// uniqid gives 13 chars, but you could adjust it to your needs.
if (function_exists("random_bytes")) {
$bytes = random_bytes(ceil($lenght / 2));
} elseif (function_exists("openssl_random_pseudo_bytes")) {
$bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
} else {
throw new Exception("no cryptographically secure random function available");
}
return substr(bin2hex($bytes), 0, $lenght);
}

Generate unique random alphanumeric using javascript

Here's something that would return only unique alphanumerics

function alphanumeric_unique() {
return Math.random().toString(36).split('').filter( function(value, index, self) {
return self.indexOf(value) === index;
}).join('').substr(2,8);
}

FIDDLE

Splitting the string into an array of characters, then using Array.filter() to filter out any characters that are already in the array to get only one instance of each character, and then finally joining the characters back to a string, and running substr(2, 8) to get the same length string as in the question, where it starts at the second character and gets a total of eight characters.

How to generate a unique alphanumeric string with atleast a number?

The OR || will return true if one of both conditions is true, so if there is no number it will pass the if clause.

You could check if both conditions are true instead:

if ($number && $uppercase) {
// do something with $values
}

Running this again $func(); inside the if clause, will run the function again generating a new string and returns $randomString; from the function.

If you want to return the tested string, you can return the already tested $values

EDIT

If you don't want to return only chars A-Z or only digits, you can update the pattern to match only digit or only chars A-Z using ^\d+$ and ^[A-Z]+$

If one if the conditions is true, then do a recursive call.

protected function generate(int $length = 4): string
{
$randomString = '';

$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < $length; $i++) {
$index = random_int(0, strlen($characters) - 1);
$randomString .= $characters[$index];
}

$uppercase = preg_match('@^[A-Z]+$@', $randomString);
$number = preg_match('@^\d+$@', $randomString);


if ($uppercase || $number) {
$randomString = $this->generate();
}

return $randomString;
}

See a PHP demo.

Creating a unique alphanumeric 10-character string

There should be no difference in the randomness of any given bit of a SHA-1 hash, so that's possible. Another way would be to fold the hash into itself using XOR until you have 60 bits worth of data, then encode it using Base 64 to get a mostly alpha-numeric result.

This is only necessary if you want to be able to generate the same Id repeatedly for the same input data. Otherwise, if a random id that you generate once, and hold onto after that, use Anders' suggestion. If you get a conflict, just generate another one.

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();
}


Related Topics



Leave a reply



Submit