Search code examples
phplinuxwindowscompatibilitycsrf-protection

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


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..

My question: is this solution ok? or is there a better way?Thanks for your helps..

Php version : 5.5.12


Solution

  • You should use openssl_random_pseudo_bytes() to generate random strings for two reason:

    1. As safe as using /dev/random
    2. Can be use in either Windows or Linux

    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;
    }