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.
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?
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?
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.
The str_shuffle() function randomly shuffles all the characters of a string.
rand() or mt_rand() functions can be used to Generate 5 Digit Random Number in PHP.
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
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With