jjzjj

php - Linux to windows compatibility with dev/urandom,有没有更好的方法?

coder 2024-06-11 原文

您好,我想使用一个名为 Kunststube-CSRFP 的包在我的项目上

问题是包会在 Windows 机器上抛出异常,因为 dev/random 对于 Windows 不合法..

导致异常的函数如下..

protected function getRandomHexStringFromDevRandom($length) {
        static $sources = array('/dev/urandom', '/dev/random');
        foreach ($sources as $source) {
            if (@is_readable($source)) {
                return bin2hex(file_get_contents($source, false, null, -1, $length / 2));
            }
        }
        throw new \RuntimeException('No system source for randomness available.');
    }

根据 php.net也可以使用 mcrypt_create_iv 函数.. 这是我解决这个兼容性问题的方法..

protected function getRandomHexStringFromDevRandom($length) {
        //static $sources = array('/dev/urandom', '/dev/random');
        srand(time());
        $iv = mcrypt_create_iv($length, MCRYPT_RAND);

        if($iv){
          return bin2hex($iv);
        }
        throw new \RuntimeException('No system source for randomness available.');
    }

我没有 linux 机器来测试这两个函数是否返回相似的输出..

我的问题:这个解决方案可以吗?或者有更好的方法吗?感谢您的帮助..

PHP 版本:5.5.12

最佳答案

您应该使用 openssl_random_pseudo_bytes() 生成随机字符串,原因有二:

  1. 与使用 /dev/random 一样安全>
  2. 可以在 Windows 或 Linux 中使用

但是你必须在 PHP 中启用 OpenSSL 扩展,否则你会得到错误。

代码:

protected function getRandomHexStringFromDevRandom($length) {
    if(!extension_loaded("openssl")){
        throw new \RuntimeException("OpenSSL extension not loaded");
    }
    $cstrong = false;
    while(!$cstrong) {
        $rand = openssl_random_pseudo_bytes($length, $cstrong);
    }
    return $rand;
}

关于php - Linux to windows compatibility with dev/urandom,有没有更好的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34836956/

有关php - Linux to windows compatibility with dev/urandom,有没有更好的方法?的更多相关文章

随机推荐