Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP fast random string function

I need fast way for generating random strings a-Z0-9 in PHP. I've been doing some thinking and testing, this is what I've got so far:

function randStr($length) {
    $result = null;
    $replace = array('/', '+', '=');
        while(!isset($result[$length-1])) {
        $result.= str_replace($replace, NULL, base64_encode(mcrypt_create_iv($length, MCRYPT_RAND)));
        }
    return substr($result, 0, $length);
}

Function seems to be working fast compared to functions which iterate and choose random ASCII value for each char, but I'm concerned with 'quality' of my implementation. I do not know much about cryptography, so I'd like to ask whether this kind of function creates 'good' random values or not.

  1. mcrypt_create_iv seems to return some kind of random binary values, actually used for encrypting/decrypting data with mcrypt library. What is base64_encode effect on this kind of binary data, do I actually decrease entropy, when I base64_encode it?

  2. How does second parameter for mcrypt_create_iv affect my results? php.net manual states that MCRYPT_RAND is 'system random number generator'. Is it OS specific and if so, how good values are created?

like image 280
Mikk Avatar asked Jan 21 '11 09:01

Mikk


People also ask

What is rand() in PHP?

Definition and Usage The rand() function generates a random integer. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function.

What does Str_shuffle do in PHP?

The str_shuffle() function randomly shuffles all the characters of a string.

How can I generate 5 random numbers in PHP?

rand() or mt_rand() functions can be used to Generate 5 Digit Random Number in PHP.


2 Answers

This supposed to be secure on most of the systems and fast:

bin2hex(openssl_random_pseudo_bytes($length / 2));

benchmarks (1000000 records, string length 100 chars)

rstr1: 198.93383002281
rstr2: 35.5827729702
rstr3: 6.8811790943146
rstr4: 5.4545040130615
this:: 3.9310231208801
like image 57
Afanasii Kurakin Avatar answered Sep 21 '22 09:09

Afanasii Kurakin


For anyone looking for an updated version of the "best" algorithm:

function randomString($length) {
   $result = null;
   $replace = array('/', '+', '=');
   while(!isset($result[$length-1])) {
      $result.= str_replace($replace, NULL, base64_encode(random_bytes($length)));
   }
   return substr($result, 0, $length);
}

I use the term "best" because it is faster than the random string manipulations of rstr1 and rstr2 and in comparison to the other solutions offers a full spectrum of letters (lower- and uppercased).

like image 45
Joseph Avatar answered Sep 19 '22 09:09

Joseph