尝试让openssl_encrypt工作的问题

时间:2013-07-22 16:15:33

标签: php openssl

我正在写一个类来处理加密数据,本质上它将用于加密要存储在数据库中的数据,然后再次在检索时对其进行解密。

这是我写的:

    class dataEncrypt {

        private $encryptString;
        private $decryptString;
        private $encryptionMethod;
        private $key;

        public function __construct() {

            /* IMPORTANT - DONT CHANGE OR DATA WILL DAMAGE */
            $this->key = sha1('StringToHash');

            // Set the encryption type
            $this->encryptionMethod = "AES-256-CBC";

        }

        // Generate the IV key
        private function generateIV() {

            $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
            return mcrypt_create_iv($ivSize, MCRYPT_RAND);
        }

        // Retrieve the key
        private function retrieveKey() {

            return $key;
        }

        // Encrypt a string
        public function encryptString($string) {

            // Return the encrypted value for storage
            return openssl_encrypt($string, $this->encryptionMethod, $this->retrieveKey(), 0, $this->generateIV());
        }

        // Decrypt a string
        public function decryptString($data) {

            // return the decrypted data
            return openssl_decrypt($data, $this->encryptionMethod, $this->retrieveKey(), 0, $this->generateIV());

            return false;

        }

    }

我正在尝试在存储之前加密字符串,并且我收到以下PHP警告:

  

警告:openssl_encrypt():传递的IV长度为32个字节,长于选定密码所期望的16个字节,在xxx行上的/ var / www / blahblah中截断

我用谷歌搜索了这个,我用谷歌搜索了IV函数,我也找不到甜心。欢迎任何建议。

由于

1 个答案:

答案 0 :(得分:9)

我能够通过将MCRYPT_CAST_256而不是MCRYPT_RIJNDAEL_256传递给mcrypt_get_iv_size来实现它的工作

加密:

$iv_size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

$encrypted = openssl_encrypt($string, "AES-256-CBC", $key, 0, $iv);
$encrypted = $iv.$encrypted;

解密

$iv_size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CBC);
$iv = substr($string, 0, $iv_size);

$decrypted = openssl_decrypt(substr($string, $iv_size), "AES-256-CBC", $key, 0, $iv);