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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With