Linux到windows兼容dev/urandom,有没有更好的办法?

Linux to windows compatibility with dev/urandom,Is there a better approach?

你好,我想在我的项目中使用一个名为 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 机器来测试两个函数的 returns 输出是否相似..

我的问题:这个方案可以吗?还是有更好的方法?感谢您的帮助..

Php 版本:5.5.12

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

  1. 与使用 /dev/random
  2. 一样安全
  3. 可用于 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;
}