Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a unique and seemingly random 5 character string

I'm trying to create a short, 5 or 6 character, invitation code that will be generated upon the creation of a "group" on my site. The group info is stored in the group table. Users wishing to join a group must have an invitation code--it isn't necessary that they know anything else.

Obviously, I need the invitation code to be unique, and I am hoping to generate unique strings without a double check, but figuring out the code has been difficult. I've been reading dozens of SO questions and answers. This is what I've come up with:

When inserting the group info, such as name, into the group table, the row is given a unique, auto-incrementing id, naturally.

1) Grab that id

2) add it to 1234

3) simply put the values next to eachother after converting the team name from base36 to base10 eg. "NewYorkYankees" is base10(3994055806027582482648) [1263399405580602758248264820130221060827])

4) convert to base 36

5) INSERT the code into the database

This is guaranteed to be unique for every group, right? Zero chance of collision? I say this because it isn't at all random; I start with something unique, and I keep it unique, never introducing random data.

I have a couple issues though, since group names are repeatable, how do I grab the row id upon creation/INSERTion? This won't work, but it's where I'm at:

$query = "SELECT id FROM groups WHERE gname = :gname";
...
$uid = $result + '1234';
$hex = md5(":gname NOW()" . uniqid("$uid", true));
base_convert($hex, 10, 36);
intval($str, 36);

$query = "INSERT...";

Unique, short, but unpredictable without all the right pieces, which aren't available to users.

like image 388
David Avatar asked Feb 21 '13 11:02

David


1 Answers

It's described here how to get the last inserted auto_increment value.

After having an ID you need to use symmetric key encryption like AES with a secret key. It is guaranteed to be unique (as it can be transformed back to the original plaintext - which is called decryption).

You can tune the block size to get the desired length (in bits). With base64 the length will be a multiple of 4 (as 8bit characters are encoded in triplets, resulting in a 4 character block in base64).

like image 55
vbence Avatar answered Sep 23 '22 11:09

vbence