cipher class and mcrypt_create_iv is slow at times

亡梦爱人 提交于 2019-12-22 03:22:56

问题


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?


回答1:


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.




回答2:


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.




回答3:


class Cipher {
    private $securekey, $iv;
    function __construct() {
        $this->securekey = hash('sha256','51(^8k"12cJ[6&cvo3H/!2s02Uh46vuT4l7sc7a@cZ27Q',TRUE);
        $this->iv = isset($_SESSION['sifrem'])?$_SESSION['sifrem']:mcrypt_create_iv(34);
        $_SESSION['sifrem']=$this->iv;
    }
    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;
    }
}


来源:https://stackoverflow.com/questions/10916221/cipher-class-and-mcrypt-create-iv-is-slow-at-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!