common_good_rand was _not_ a "good rand", only hex

0-F isn't random enough to be called rand, so we rename the function
to avoid confusion with something that is actually good at random.
This commit is contained in:
Mikael Nordfeldth 2013-10-21 13:09:40 +02:00
parent df5aa6f93a
commit db5df642ba

View File

@ -1550,15 +1550,25 @@ function common_root_url($ssl=false)
/** /**
* returns $bytes bytes of random data as a hexadecimal string * returns $bytes bytes of random data as a hexadecimal string
* "good" here is a goal and not a guarantee * "good" here is a goal and not a guarantee
*
* TODO: Find and replace all calls to this with common_random_hexstr
*/ */
function common_good_rand($bytes) function common_good_rand($bytes)
{ {
// XXX: use random.org...? return common_random_hexstr($bytes);
if (@file_exists('/dev/urandom')) { }
return common_urandom($bytes);
} else { // FIXME: this is probably not good enough function common_random_hexstr($bytes)
return common_mtrand($bytes); {
$str = @file_exists('/dev/urandom')
? common_urandom($bytes)
: common_mtrand($bytes);
$hexstr = '';
for ($i = 0; $i < $bytes; $i++) {
$hexstr .= sprintf("%02x", ord($str{$i}));
} }
return $hexstr;
} }
function common_urandom($bytes) function common_urandom($bytes)
@ -1567,20 +1577,16 @@ function common_urandom($bytes)
// should not block // should not block
$src = fread($h, $bytes); $src = fread($h, $bytes);
fclose($h); fclose($h);
$enc = ''; return $src;
for ($i = 0; $i < $bytes; $i++) {
$enc .= sprintf("%02x", (ord($src[$i])));
}
return $enc;
} }
function common_mtrand($bytes) function common_mtrand($bytes)
{ {
$enc = ''; $str = '';
for ($i = 0; $i < $bytes; $i++) { for ($i = 0; $i < $bytes; $i++) {
$enc .= sprintf("%02x", mt_rand(0, 255)); $str .= chr(mt_rand(0, 255));
} }
return $enc; return $str;
} }
/** /**