note 105587 modified in function.mt-rand by danbrown

From: Date: Tue, 30 Aug 2011 17:17:20 +0000
Subject: note 105587 modified in function.mt-rand by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-182830@lists.php.net to get a copy of this message
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; } ?> --was-- 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! 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; } http://php.net/manual/en/function.mt-rand.php

« previous php.notes (#182830) next »