您好,我想使用一个名为 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() 生成随机字符串,原因有二:
/dev/random 一样安全>但是你必须在 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/