使用OpenCart CMS的OpenSSL Encription替换Mcrypt Encription

时间:2018-07-03 17:35:04

标签: php encryption openssl opencart mcrypt

我在OpenCart 1.5.6.4中有encryption.phpsystem library folder文件。
encryption.php中的代码是:

<?php
final class Encryption {
    private $key;
    private $iv;

    public function __construct($key) {
        $this->key = hash('sha256', $key, true);
        $this->iv = mcrypt_create_iv(32, MCRYPT_RAND);
    }

    public function encrypt($value) {
        return strtr(base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->key, $value, MCRYPT_MODE_ECB, $this->iv)), '+/=', '-_,');
    }

    public function decrypt($value) {
        return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->key, base64_decode(strtr($value, '-_,', '+/=')), MCRYPT_MODE_ECB, $this->iv));
    }
}
?>

要从php 5.6迁移到php 7.2,我需要将Mcrypt Encription替换为OpenSSL Encription
我已将mcrypt_create_iv(32, MCRYPT_RAND)替换为openssl_random_pseudo_bytes(32, true),但是对于encrypt functiondecrypt function,我不知道这些功能要使用什么parameters
encription.php代码需要进行哪些更改?

1 个答案:

答案 0 :(得分:0)

我本来wrote this是为了解决current encryption class for OC3附带的空iv警告:

  

警告:openssl_encrypt():使用空的初始化向量(iv)可能不安全,因此不建议使用

由于您发布此问题的确切原因,最近又将其反向移植到OC1.5。这是system/library/encryption.php的替代品,将在OC1.5.6.4和PHP7.2上完全替代:

final class Encryption {

    private $cipher = 'aes-256-ctr';
    private $digest = 'sha256';
    private $key;

    public function __construct($key) {
        $this->key = $key;
    }

    public function encrypt($value) {
        $key       = openssl_digest($this->key, $this->digest, true);
        $iv_length = openssl_cipher_iv_length($this->cipher);
        $iv        = openssl_random_pseudo_bytes($iv_length);
        return base64_encode($iv . openssl_encrypt($value, $this->cipher, $key, OPENSSL_RAW_DATA, $iv));
    }

    public function decrypt($value) {
        $result    = NULL;
        $key       = openssl_digest($this->key, $this->digest, true);
        $iv_length = openssl_cipher_iv_length($this->cipher);
        $value     = base64_decode($value);
        $iv        = substr($value, 0, $iv_length);
        $value     = substr($value, $iv_length);
        if (strlen($iv) == $iv_length) {
            $result = openssl_decrypt($value, $this->cipher, $key, OPENSSL_RAW_DATA, $iv);
        }
        return $result;
    }
}