note 104322 added to function.openssl-random-pseudo-bytes
| From: | christophe dot weis at statec dot etat dot lu | Date: | Thu, 09 Jun 2011 07:09:57 +0000 |
| Subject: | note 104322 added to function.openssl-random-pseudo-bytes | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-180347@lists.php.net to get a copy of this message | ||
Another replacement for rand() using OpenSSL.
Note that a solution where the result is truncated using the modulo operator ( % ) is not
cryptographically secure, as the generated numbers are not equally distributed, i.e. some numbers
may occur more often than others.
A better solution than using the modulo operator is to drop the result if it is too large and
generate a new one.
<?php
function crypto_rand_secure($min, $max) {
$range = $max - $min;
if ($range == 0) return $min; // not so random...
$log = log($range, 2);
$bytes = (int) ($log / 8) + 1; // length in bytes
$bits = (int) $log + 1; // length in bits
$filter = (int) (1 << $bits) - 1; // set all lower bits to 1
do {
$rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes, $s)));
$rnd = $rnd & $filter; // discard irrelevant bits
} while ($rnd >= $range);
return $min + $rnd;
}
?>
----
Server IP: 69.147.83.197
Probable Submitter: 194.154.200.108
----
Manual Page -- http://www.php.net/manual/en/function.openssl-random-pseudo-bytes.php
Edit -- https://master.php.net/note/edit/104322
Del: integrated -- https://master.php.net/note/delete/104322/integrated
Del: useless -- https://master.php.net/note/delete/104322/useless
Del: bad code -- https://master.php.net/note/delete/104322/bad+code
Del: spam -- https://master.php.net/note/delete/104322/spam
Del: non-english -- https://master.php.net/note/delete/104322/non-english
Del: in docs -- https://master.php.net/note/delete/104322/in+docs
Del: other reasons-- https://master.php.net/note/delete/104322
Reject -- https://master.php.net/note/reject/104322
Search -- https://master.php.net/manage/user-notes.php