replace rand() with openssl_random_pseudo_bytes()

2019-01-23 04:36发布

I need a replacement for PHP's rand() function that uses a cryptographically strong random number generator.

The openssl_random_pseudo_bytes() function gets you access to the strong random number generator, but it outputs its data as a byte string. Instead, I need an integer between 0 and X.

I imagine the key is to get the output of openssl_random_pseudo_bytes() into an integer, then you can do any math on it that you need to. I can think of a few "brute force" ways of converting from a byte string to an integer, but I was hoping for something ... elegant.

7条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-23 05:20

Heres a version of the solutions above, which doesn't use recursive function calls:

function secure_rand($min,$max) {
    $range = $max - $min + 1;
    if ($range == 0) return $min;
    $length = (int) (log($range,2) / 8) + 1;
    $max = pow(2, 8 * $length);
    $num = $max + 1; // Hackish, I know..
    while ($num > $max) {
        $num = hexdec(bin2hex(openssl_random_pseudo_bytes($length,$s)));
    }
    return ($num  % $range) + $min;
}
查看更多
登录 后发表回答