/dev/urandom 错误(网站主机拒绝许可)

/dev/urandom error (permission denied by webhost)

我正在使用函数:

private function random($len) {
        if (@is_readable('/dev/urandom')) {
            $f=fopen('/dev/urandom', 'r');
            $urandom=fread($f, $len);
            fclose($f);
        }

        $return='';
        for ($i=0;$i<$len;++$i) {
            if (!isset($urandom)) {
                if ($i%2==0) mt_srand(time()%2147 * 1000000 + (double)microtime() * 1000000);
                $rand=48+mt_rand()%64;
            } else $rand=48+ord($urandom[$i])%64;

            if ($rand>57)
                $rand+=7;
            if ($rand>90)
                $rand+=6;

            if ($rand==123) $rand=52;
            if ($rand==124) $rand=53;
            $return.=chr($rand);
        }
        return $return;
    }

我有一些触发此功能的表格,但我收到错误消息:

int(2) string(200) "is_readable(): open_basedir restriction in effect. File(/dev/urandom) is not within the allowed path(s):

有没有办法代替这个功能而不用/dev/urandom? 非常感谢。

来自(先前接受的)答案:

Instead of urandom you can use "rand":

不不不不!


处理 open_basedir 是我们在 random_compat 中优雅处理的事情之一。认真考虑导入该库,然后只使用 random_bytes() 而不是从 /dev/urandom.

读取

无论你做什么,DON'T USE rand(). Even if you believe there's a use case for it, the security trade-offs are a lie

此外,如果您需要一个函数来生成随机字符串(取决于 PHP 7 或 random_compat):

/**
 * Note: See https://paragonie.com/b/JvICXzh_jhLyt4y3 for an alternative implementation
 */
function random_string($length = 26, $alphabet = 'abcdefghijklmnopqrstuvwxyz234567')
{
    if ($length < 1) {
        throw new InvalidArgumentException('Length must be a positive integer');
    }
    $str = '';
    $alphamax = strlen($alphabet) - 1;
    if ($alphamax < 1) {
        throw new InvalidArgumentException('Invalid alphabet');
    }
    for ($i = 0; $i < $length; ++$i) {
        $str .= $alphabet[random_int(0, $alphamax)];
    }
    return $str;
}

演示代码:https://3v4l.org/DOjNE

如果您的主机不支持 random_int(),您可以使用我为自己制作的功能。

function generateRandomString($length, $secureRand = false, $chars="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") {
    if (!function_exists("random_int") && $secureRand) {
        function random_int($min, $max) {
            $range = $max - $min;
            if ($range <= 0) return $min;

            $log = ceil(log($range, 2));
            $bytes = (int)($log / 8) + 1;
            $filter = (int)(1 << ((int)($log + 1))) - 1;
            do {
                $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes, $s)));
                if (!$s) continue;
                $rnd = $rnd & $filter;
            } while ($rnd > $range);

            return $min + $rnd;
        }
    }

    $charsCount = strlen($chars) - 1;
    $output = "";
    for ($i=1; $i <= $length; $i++) {
        if ($secureRand)
            $output .= $chars[random_int(0, $charsCount)];
        else
            $output .= $chars[mt_rand(0, $charsCount)];
    }
    return $output;
}

如果您需要安全的随机字符串(例如随机密码):

generateRandomString(8, true);

这会给你一个 8 长的字符串。