Andrew L
Andrew L

Reputation: 141

Function similar to MD5() for random string generation (preferably crypto-secure)

Currently working on a PHP project where I need to create a 9 character key, and recently came upon the MD5() function which I know is capable of creating a 32 character randomization, but is there anyway to shorten it down?

Is there another function that could possibly do a random number and letter combination of shorter length? I wrote a little algorithm for concatenating something similar a while back but having trouble injecting it into my code. The ID should be somewhat secure, and the DB will be checked for dups.

Upvotes: 1

Views: 408

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173642

You can use the system's pseudo random source, either directly or using a hash function:

// direct
echo substr(base64_encode(openssl_random_pseudo_bytes(7)), 0, 9);

// via hash function
echo substr(base64_encode(sha1(openssl_random_pseudo_bytes(7), true)), 0, 9);

Using Base-64 encoding generates an output space of 64 ^ 9 whereas the output of md5() has a mere 16 ^ 9 (250k times smaller). The range of this encoding is [A-Za-z0-9+/]; you can choose to substitute + and / by - and _ respectively.

See also: openssl_random_pseudo_bytes()

Update

You can remove the + and / from Base-64 by a simple transformation:

strtr($output, '/+', 'Zz');

It duplicates two letters, but in the grand scheme of things it will have little impact on its uniqueness.

Upvotes: 1

netvision73
netvision73

Reputation: 4921

Why not substr ? For example :

$code = substr(md5(time()), 0, 9);

Upvotes: 3

Ramesh
Ramesh

Reputation: 4293

You can have a look at uniqid()

https://www.php.net/uniqid

Upvotes: 1

Related Questions