CBC mode encryption / decryption issue in php mcrypt

I have a problem with CBC mode when I try to encrypt / decrypt some text using php mcrypt extension. I created a class to perform these operations, it works fine with other modes, but CBC.

The problem is as follows:

I use the text Even in cryptography, silence is golden . I am doing part of the encryption, no problem up to this point. But every time I try to decrypt, I get something like this: 9 't" cryptography, silence is golden . As you can see, the first 8 characters of the text are wrong. I don’t know what could be the reason for this behavior.

The parts of my class that handle these operations are:

 public function encrypt($data) { $cypher = $this->_getCypher(); $iv = $this->_getIv($cypher); return trim(base64_encode(mcrypt_encrypt($cypher, self::KEY, $data, MCRYPT_MODE_CBC, $iv))); } public function decrypt($data) { $cypher = $this->_getCypher(); $iv = $this->_getIv($cypher); return trim(mcrypt_decrypt($cypher, self::KEY, base64_decode($data), MCRYPT_MODE_CBC, $iv)); } protected function _getCypher() { return self::$_cyphers[$this->_algorithm]; } protected function _getIv($cypher) { return mcrypt_create_iv(mcrypt_get_iv_size($cypher, MCRYPT_MODE_CBC), MCRYPT_RAND); } 

And the algorithm used for the above example is 3DES. As I said, when using another mode, such as ECB, everything works fine.

Any suggestions?

+4
source share
1 answer

You need to remember the IV that you used for encryption, and use it again for decryption.

+3
source

All Articles