I have a problem with CBC mode when I try to encrypt/decrypt some text using php's mcrypt extension. I've created a class to perform this operations, it works fine with other modes but CBC.
The problem is as follow:
I use the clear text Even in cryptography, silence is golden
. I do the encryption part, no problem till this point. But each time I try to decrypt, I get something like this: . As you can see, the first 8 characters of the text are wrong. I don't know what may be causing this behavior.
The parts of my class which 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 above example is 3DES. As I said before, using other mode, such as ECB, everything works fine.
Any suggestions ?