From e74f05efb6194276a2b0c302a7764ee8a362c593 Mon Sep 17 00:00:00 2001 From: Ivan Tcholakov Date: Sun, 21 Dec 2014 17:03:46 +0200 Subject: [PATCH] Corrections about random bytes generation, dealing with some PHP versions. --- GibberishAES.php | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/GibberishAES.php b/GibberishAES.php index 67ce41f..883aa3f 100644 --- a/GibberishAES.php +++ b/GibberishAES.php @@ -12,11 +12,11 @@ * * OpenSSL functions installed and PHP version >= 5.3.3 (preferred case) * or - * Mcrypt functions installed. + * Mcrypt functions installed. * * If none of these functions exist, the class will try to use openssl * from the command line (avoid this case). - * + * * Usage: * * // This is a secret key, keep it in a safe place and don't loose it. @@ -42,11 +42,11 @@ * $decrypted_string = GibberishAES::dec($encrypted_string, $key); * GibberishAES::size($old_key_size); * echo $decrypted_string; - * + * * @author Ivan Tcholakov , 2012-2014. * Code repository: @link https://github.com/ivantcholakov/gibberish-aes-php * - * @version 1.1 + * @version 1.1.1 * * @license The MIT License (MIT) * @link http://opensource.org/licenses/MIT @@ -58,6 +58,7 @@ class GibberishAES { protected static $valid_key_sizes = array(128, 192, 256); // Sizes in bits protected static $openssl_random_pseudo_bytes_exists = null; + protected static $mcrypt_dev_urandom_exists = null; protected static $openssl_encrypt_exists = null; protected static $openssl_decrypt_exists = null; protected static $mcrypt_exists = null; @@ -200,13 +201,30 @@ public static function size($newsize = null) { protected static function random_pseudo_bytes($length) { if (!isset(self::$openssl_random_pseudo_bytes_exists)) { - self::$openssl_random_pseudo_bytes_exists = function_exists('openssl_random_pseudo_bytes'); + + self::$openssl_random_pseudo_bytes_exists = function_exists('openssl_random_pseudo_bytes') && + (version_compare(PHP_VERSION, '5.3.4') >= 0 || substr(PHP_OS, 0, 3) !== 'WIN'); } if (self::$openssl_random_pseudo_bytes_exists) { return openssl_random_pseudo_bytes($length); } + if (!isset(self::$mcrypt_dev_urandom_exists)) { + + self::$mcrypt_dev_urandom_exists = function_exists('mcrypt_create_iv') && + (version_compare(PHP_VERSION, '5.3.7') >= 0 || substr(PHP_OS, 0, 3) !== 'WIN'); + } + + if (self::$mcrypt_dev_urandom_exists) { + + $rnd = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); + + if ($rnd !== false) { + return $rnd; + } + } + // Borrowed from http://phpseclib.com/ $rnd = '';