Skip to content

Commit

Permalink
Corrections about random bytes generation, dealing with some PHP vers…
Browse files Browse the repository at this point in the history
…ions.
  • Loading branch information
ivantcholakov committed Dec 21, 2014
1 parent 43cbe89 commit e74f05e
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions GibberishAES.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -42,11 +42,11 @@
* $decrypted_string = GibberishAES::dec($encrypted_string, $key);
* GibberishAES::size($old_key_size);
* echo $decrypted_string;
*
*
* @author Ivan Tcholakov <[email protected]>, 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
Expand All @@ -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;
Expand Down Expand Up @@ -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 = '';
Expand Down

0 comments on commit e74f05e

Please sign in to comment.