ThePHPUnicorn
ThePHPUnicorn

Reputation: 619

issues trying to get openssl_encrypt to work

I'm writing a class to handle encrypted data, essentially it will be used to encrypt data to be stored in a DB and then again to decrypt it on retrieval.

Here's what I've written:

    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;

        }

    }

I'm trying to encrypt a string before storing, and I get the following PHP warning:

Warning: openssl_encrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher, truncating in /var/www/blahblah... on line xxx

I've googled this, Ive googled the IV functions, I can't find sweetheat on either. Any advice is welcomed here.

Thanks

Upvotes: 5

Views: 8272

Answers (1)

ChrisKnowles
ChrisKnowles

Reputation: 7100

I was able to get it working by passing MCRYPT_CAST_256 rather than MCRYPT_RIJNDAEL_256 into mcrypt_get_iv_size

Encrypt:

$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;

Decrypt

$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);

Upvotes: 10

Related Questions