-3

Hi I found this script.

The script:

function urandom_rand($min = 0, $max = 0x7FFFFFFF){
$min = (int)$min;
$max = (int)$max;
if ($max <= $min)
    trigger_error('Minimum value must be greater than maximum value.');
if ($min < 0 || $max > 0x7FFFFFFF)
    trigger_error('Values must be between 0 and 2147483647.');

$M = bcadd(0x7FFFFFFF,1); // (up bound of iv)+1
$N = bcadd($max-$min, 1); // how many different values this function can return
$h = bcmod($M, $N); // the last h integers from unpack are "invalids"

do{
    $bytes = mcrypt_create_iv(4, MCRYPT_DEV_URANDOM);
    $r = unpack("N", $bytes)[1] & 0x7FFFFFFF;
} while ($r > ($M-$h));
return (bcmod($r, $N) + $min);
}

My question is: Is this script a good solution for the generation of random numbers?

1 Answers1

0

That function may work, but don't reinvent the wheel.

Why not just use PHP's build in int rand ( int $min , int $max ) or int mt_rand ( int $min , int $max ) function?

The main difference is mt_rand is faster and the sudo random numbers are not as easy to predict.

If you need cryptographic randomness, it has been suggested to use int random_int ( int $min , int $max ) in php 7. On older php versions, use openssl_random_pseudo_bytes, and check the crypto_strong parameter to verify that the number generated is cryptographically strong.

Community
  • 1
  • 1
L Bahr
  • 2,723
  • 3
  • 22
  • 25
  • 1
    No, `mt_rand()` is actually *easier* to predict. It was created because of a perception that `rand()` was "too slow". Both generate numbers algorithmically, and will produce a repeatable sequence of numbers for a given seed. These PRNGs are fine for minor uses, but if you need a CSPRNG there is [`random_int()`](http://php.net/manual/en/function.random-int.php) in PHP7 and [`random_compat`](https://github.com/paragonie/random_compat) that backports it to PHP5. – Sammitch Apr 15 '16 at 17:20
  • 1
    It may be true that given the same seed they will produce the same output, ["but mathematically mt_rand have more entropy than rand"](http://stackoverflow.com/a/28760933/6194193). Therefore rand() would be easier to predict as my answer stated. For an example of how the two compare look at [Followup: PHP: rand() vs. mt_rand()](http://web.archive.org/web/20140801002727/http://tjl.co/blog/code/followup-php-rand-vs-mt_rand/) – L Bahr Apr 15 '16 at 17:30
  • 1
    I updated my answer with your suggestion about cryptographic randomness with random_int() @Sammitch – L Bahr Apr 15 '16 at 17:39