Hi i want to use a package called Kunststube-CSRFP on my project
Problem is the package will throw an exception on windows machines because dev/random is not legit for Windows..
The function causes the exception is below..
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.');
}
According to php.net one can also use mcrypt_create_iv function.. And here is my approach to solve this compatibility problem..
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.');
}
I don't have a linux machine to test if both function's returns similar outputs..
Php version : 5.5.12
You should use openssl_random_pseudo_bytes()
to generate random strings for two reason:
/dev/random
But you have to enable the OpenSSL extension in PHP otherwise you will get error.
Code:
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;
}