嗨,我想在我的项目中使用一个名为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到Windows与dev/urandom的兼容性,是否有更好的方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34836956/