Unique Random String Generation

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

Generating Unique Random Strings

What you do now is you generate a random string c then print it 10 times
You should instead place the generation inside the loop to generate a new string every time.

import random
import string

s = string.ascii_lowercase

for i in range(10):
c = ''.join(random.choice(s) for i in range(8))
print(c)

Laravel unique random string number

To guarantee a unique number you should instead use created. Whenever a ticket is created, you can prepend some random numbers to the id to generate a unique number. Try this

public function created(Ticket $ticket) {
$ticket->number = rand(1000, 9999).str_pad($ticket->id, 3, STR_PAD_LEFT);
$ticket->save();
}

Generate a unique random string in R using stringi

You can use the ids package to create unique ID's automatically. For instance, to make 10 million user ID's, you could use:

randos <- ids::random_id(1E6, 4)
# The 2nd term here controls how many bytes are assigned to each ID.
# The default, 16 bytes, makes much longer IDs and crashes my computer

head(randos)
#[1] "31ca372d" "d462e55f" "2374cc78" "15511574" "ecbf2d65" "236cb2d3"

It has other nice features, like the adjective_animal function, which creates IDs that are easier for humans to distinguish and remember.

creatures <- ids::adjective_animal(1E6, n_adjectives = 1)
head(creatures)
#[1] "yestern_lizard" "insensible_purplemarten"
#[3] "cubical_anhinga" "theophilic_beaver"
#[5] "subzero_greyhounddog" "hurt_weasel"

Generate random string/characters in JavaScript

I think this will work for you:

function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}

console.log(makeid(5));

Unique random string generation

Using Guid would be a pretty good way, but to get something looking like your example, you probably want to convert it to a Base64 string:

    Guid g = Guid.NewGuid();
string GuidString = Convert.ToBase64String(g.ToByteArray());
GuidString = GuidString.Replace("=","");
GuidString = GuidString.Replace("+","");

I get rid of "=" and "+" to get a little closer to your example, otherwise you get "==" at the end of your string and a "+" in the middle. Here's an example output string:

"OZVV5TpP4U6wJthaCORZEQ"

Random string generation with upper case letters and digits

Answer in one line:

''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))

or even shorter starting with Python 3.6 using random.choices():

''.join(random.choices(string.ascii_uppercase + string.digits, k=N))

A cryptographically more secure version: see this post

''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))

In details, with a clean function for further reuse:

>>> import string
>>> import random
>>> def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
... return ''.join(random.choice(chars) for _ in range(size))
...
>>> id_generator()
'G5G74W'
>>> id_generator(3, "6793YUIO")
'Y3U'

How does it work ?

We import string, a module that contains sequences of common ASCII characters, and random, a module that deals with random generation.

string.ascii_uppercase + string.digits just concatenates the list of characters representing uppercase ASCII chars and digits:

>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.ascii_uppercase + string.digits
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'

Then we use a list comprehension to create a list of 'n' elements:

>>> range(4) # range create a list of 'n' numbers
[0, 1, 2, 3]
>>> ['elem' for _ in range(4)] # we use range to create 4 times 'elem'
['elem', 'elem', 'elem', 'elem']

In the example above, we use [ to create the list, but we don't in the id_generator function so Python doesn't create the list in memory, but generates the elements on the fly, one by one (more about this here).

Instead of asking to create 'n' times the string elem, we will ask Python to create 'n' times a random character, picked from a sequence of characters:

>>> random.choice("abcde")
'a'
>>> random.choice("abcde")
'd'
>>> random.choice("abcde")
'b'

Therefore random.choice(chars) for _ in range(size) really is creating a sequence of size characters. Characters that are randomly picked from chars:

>>> [random.choice('abcde') for _ in range(3)]
['a', 'b', 'b']
>>> [random.choice('abcde') for _ in range(3)]
['e', 'b', 'e']
>>> [random.choice('abcde') for _ in range(3)]
['d', 'a', 'c']

Then we just join them with an empty string so the sequence becomes a string:

>>> ''.join(['a', 'b', 'b'])
'abb'
>>> [random.choice('abcde') for _ in range(3)]
['d', 'c', 'b']
>>> ''.join(random.choice('abcde') for _ in range(3))
'dac'


Related Topics



Leave a reply



Submit