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.

有帮助吗?

解决方案

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;
    }
}

其他提示

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

$number = ($generated % ($x + $y + 1)) - $x
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top