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 thatMCRYPT_RAND
is 'system random number generator'. Is it OS specific and if so, how good values are created?
MCRYPT_DEV_URANDOM
. It has decent performance is secure. – Lameemcrypt_create_iv($numBytes, MCRYPT_DEV_URANDOM)
is actually faster than trying to build it usingmt_rand()
. :) – Lustigmcrypt_create_iv()
is deprecated in PHP 7.1. An alternative is php.net/manual/en/function.random-bytes.php – Coherent