Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cipher class and mcrypt_create_iv is slow at times

I am having an issue with my cipher class. At times it is very fast. Sometimes however it is slow. the code Im using is as follows

class Cipher {
    private $securekey, $iv;
    function __construct() {
        $this->securekey = hash('sha256','51(^8k"12cJ[6&cvo3H/!2s02Uh46vuT4l7sc7a@cZ27Q',TRUE);
        $this->iv = mcrypt_create_iv(32);
    }
    function encrypt($input) {
        return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->securekey, $input, MCRYPT_MODE_ECB));
    }
    function decrypt($input) {
        return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->securekey, base64_decode($input), MCRYPT_MODE_ECB));
    }
    function storeIV() {
        return $this->iv;
    }
}

Are there any suggestions on why this may be slow at times and how I could fix this?

like image 286
bretterer Avatar asked Jun 06 '12 14:06

bretterer


2 Answers

Have you tried the three different second arguments for mcrypt_create_iv(): MCRYPT_RAND (system random number generator), MCRYPT_DEV_RANDOM (read data from /dev/random) and MCRYPT_DEV_URANDOM (read data from /dev/urandom)? Do they offer different consistent speeds? I wonder if it's because /dev/random (the default random source) is running out of collected entropy; the function will block when it does.

like image 143
WWW Avatar answered Nov 18 '22 00:11

WWW


Use MCRYPT_DEV_URANDOM when creating the IV. It's less secure, but won't block if entropy gets too low. MCRYPT_DEV_RANDOM will wait until enough entropy is acquired to be secure.

// PHP < 5.6
$this->iv = mcrypt_create_iv(32, MCRYPT_DEV_URANDOM);

But in more updated versions of PHP, the default has changed and your original code should work.

// PHP >= 5.6
$this->iv = mcrypt_create_iv(32);   // MCRYPT_DEV_URANDOM implied

PHP docs: mcrypt_create_iv (note on $source parameter):

Note that the default value of this parameter was MCRYPT_DEV_RANDOM prior to PHP 5.6.0.

And from Ubuntu Manual:

If you are unsure about whether you should use /dev/random or /dev/urandom, then probably you want to use the latter. As a general rule, /dev/urandom should be used for everything except long-lived GPG/SSL/SSH keys.

like image 37
rich remer Avatar answered Nov 18 '22 00:11

rich remer