php - 将 rand() 替换为 openssl_random_pseudo_bytes()

标签 php random cryptography

我需要替换 PHP 的 rand() 函数,该函数使用加密强度高的随机数生成器。

openssl_random_pseudo_bytes() 函数可让您访问强随机数生成器,但它会将其数据输出为字节字符串。相反,我需要一个介于 0 和 X 之间的整数。

我认为关键是将 openssl_random_pseudo_bytes() 的输出转换为整数,然后您可以根据需要对其进行任何数学运算。我可以想到一些从字节字符串转换为整数的“强力”方法,但我希望得到一些……优雅的东西。

最佳答案

根据提供的建议,我使用 OpenSSL 创建了 rand() 的替代品。我会把它包括在这里供后代使用。

$pedantic 选项通过在结果未均匀分布在可能范围内时重新开始来提供无偏差结果。

function crypto_rand($min,$max,$pedantic=True) {
    $diff = $max - $min;
    if ($diff <= 0) return $min; // not so random...
    $range = $diff + 1; // because $max is inclusive
    $bits = ceil(log(($range),2));
    $bytes = ceil($bits/8.0);
    $bits_max = 1 << $bits;
    // e.g. if $range = 3000 (bin: 101110111000)
    //  +--------+--------+
    //  |....1011|10111000|
    //  +--------+--------+
    //  bits=12, bytes=2, bits_max=2^12=4096
    $num = 0;
    do {
        $num = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes))) % $bits_max;
        if ($num >= $range) {
            if ($pedantic) continue; // start over instead of accepting bias
            // else
            $num = $num % $range;  // to hell with security
        }
        break;
    } while (True);  // because goto attracts velociraptors
    return $num + $min;
}

关于php - 将 rand() 替换为 openssl_random_pseudo_bytes(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1313223/

相关文章:

algorithm - 生成没有重复的随机序列

java - AES javascript加密和Java解密

php - 是否可以使用 call_user_func_array() 通过引用传递参数?

php - : Duplicate values in array when query is run 的问题

c++ - 在每次调用 : should I pass the engine, 分配或两者时生成不同数字的函数?

python - CTR 中的 AES 如何与 PyCrypto 一起用于 Python?

c - Miller Rabin Primality 测试精度

php - curl 同一服务器时找不到 404

php - 如何在不更改文件夹的情况下更改网址?

r - 具有指定均值的样本整数值