note 105587 deleted from function.mt-rand by cmb
| From: | cmb@php.net | Date: | Sun, 31 Mar 2019 08:36:43 +0000 |
| Subject: | note 105587 deleted from function.mt-rand by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-210462@lists.php.net to get a copy of this message | ||
Note Submitter: rok dot kralj at rok-kralj dot net
----
This function has limited entrophy. So, if you want to create random string, it will produce only
about 2 billion different strings, no matter the length of the string. This can be serous security
issue if you are using such strings for session indentifiers, passwords etc.
Many times I have wanted to create *propper* base-64 string (containing only printable characters)
of arbitrary length for many purposes. I wrote a function that checks if UNIX random generator is
available and uses in that case. If not, it tries to increase the entrophy by accounting in the
script execution time.
Here is the function, just try it out!
<?php
function random($len) {
if (@is_readable('/dev/urandom')) {
$f=fopen('/dev/urandom', 'r');
$urandom=fread($f, $len);
fclose($f);
}
$return='';
for ($i=0;$i<$len;++$i) {
if (!isset($urandom)) {
if ($i%2==0) mt_srand(time()%2147 * 1000000 + (double)microtime() * 1000000);
$rand=48+mt_rand()%64;
} else $rand=48+ord($urandom[$i])%64;
if ($rand>57)
$rand+=7;
if ($rand>90)
$rand+=6;
if ($rand==123) $rand=45;
if ($rand==124) $rand=46;
$return.=chr($rand);
}
return $return;
}
?>