gpt4 book ai didi

php - 使用 PHP 5.6 生成范围内的安全随机整数

转载 作者:行者123 更新时间:2023-12-05 00:49:58 25 4
gpt4 key购买 nike

我想在 PHP5.6 中的 $min$max 之间生成一个安全的随机整数。 PHP 中的 rand()mt_rand() 都被认为不是加密安全的。

来自 docs :

Caution

This function does not generate cryptographically secure values, and should not be used for cryptographic purposes. If you need a cryptographically secure value, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.

PHP 7 添加了 random_int() ( docs ),非常适合我的用例:

random_int — Generates cryptographically secure pseudo-random integers

但是如何在 PHP 5.6 中实现这个功能呢?

我的幼稚尝试是这样的:

<?php
function secure_rand($min, $max)
{
return (unpack("N", openssl_random_pseudo_bytes(4)) % ($max - $min)) + $min;
}

但我在调用 secure_rand(1, 100) 时似乎总是得到“2”。我还读过以这种方式使用模数运算会产生偏差。如何在 PHP 5.6 中模拟 random_int()

最佳答案

我可以给你介绍random_compat吗? , PHP 5 项目中的 random_bytes()random_int() 有哪些 polyfill? (旁注:在其他项目中,它正在被 Wordpress 在 4.4 中采用。)

function secure_rand($min, $max)
{
return (unpack("N", openssl_random_pseudo_bytes(4)) % ($max - $min)) + $min;
}

即使这是在做你想让它做的事情,这也是一个 biased random number generator($max - $min) 不是 2 的偶次幂时。

关于php - 使用 PHP 5.6 生成范围内的安全随机整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32732940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com