Get Negative Numbers With OpenSSL Random In PHP

2019-08-04 16:56发布

I'm messing around with some code to make a strong pseudo-random number generator using PHP. So far, I have the following.

function strongRand($bytes, $min, $max)
{
    if(function_exists('openssl_random_pseudo_bytes'))
    {
        $strong = true;
        $n = 0;

        do{
            $n = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes, $strong)));
        }
        while($n < $min || $n > $max);

        return $n;
    }
    else{
        return mt_rand($min, $max);
    }
}

This is almost perfect for me—except that all of the numbers that I generate with openssl_random_pseudo_bytes are positive. Ideally, I'd like to generate numbers from -x to +y. I have thought about maybe adding a another PRNG call to decide if a number should be positive or negative, but I'm not sure if that's the best way to go.

2条回答
一纸荒年 Trace。
2楼-- · 2019-08-04 17:33

You could simply add another random function, we'll use rand(0,1) this will generate 0 or 1, if it's 1 $status = 1 if it's 0 $status = -1. When we return the value we do multiplication by $status:

function strongRand($bytes, $min, $max)
{
    $status = mt_rand(0,1) === 1 ? 1:-1;

    if(function_exists('openssl_random_pseudo_bytes'))
    {
        $strong = true;
        $n = 0;

        do{
            $n = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes, $strong)));
        }
        while($n < $min || $n > $max);

        return $n * $status;
    }
    else{
        return mt_rand($min, $max) * $status;
    }
}
查看更多
放荡不羁爱自由
3楼-- · 2019-08-04 17:53

If you need to generate number from -x to +y, you can simply generate 4-byte uint, and:

$number = ($generated % ($x + $y + 1)) - $x
查看更多
登录 后发表回答