cipher class and mcrypt_create_iv is slow at times

纵饮孤独 提交于 2019-12-05 01:02:52
Crontab

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.

SALTUK BUĞRA DUMANLI
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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!