0

I have looked at this entry and tested some of the recommendations: recieving error Warning: mcrypt_decrypt(): The IV parameter must be as long as the blocksize

I have a very small pdf file (141.06 kb) that was created from a webpage using wkhtmltopdf and encrypted using this function:

public function encrypt($data) {
    if ($data !== '') {

        $iv = mcrypt_create_iv($this->iv_size, MCRYPT_DEV_URANDOM);

        $plaintext_utf8 = utf8_encode($data);
        return base64_encode($iv) . base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, Configure::read('Cryptable.key'), $plaintext_utf8, MCRYPT_MODE_CBC, $iv));
    } else {
        return '';
    }
}

As I mentioned above, I tested some of the recommendations on a SO post and found this:

iv_size = 16

length of iv = 18

Any other larger document encrypted with the same function decrypts properly so what I'm trying to figure out is how to handle very small files. Could it be that when calculating the iv on small amounts of data the result can be unpredictable?

This is the decrypt function:

public function decrypt($data, $data2 = null) {
    if (is_object($data)) {
        unset($data);
        $data = $data2;
    }

    if ($data != '') {
        $iv = base64_decode(substr($data, 0, strlen(base64_encode(mcrypt_create_iv($this->iv_size, MCRYPT_DEV_URANDOM)))));
        $data = base64_decode(substr($data, strlen(base64_encode(mcrypt_create_iv($this->iv_size, MCRYPT_DEV_URANDOM)))));

        return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, Configure::read('Cryptable.key'), $data, MCRYPT_MODE_CBC, $iv));
    } else {
        return '';
    }
}

IV size is calculated like this:

$this->iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);

Before I forget, I'm using CakePHP 2.6.4

Community
  • 1
  • 1
wp4nuv
  • 13
  • 4
  • Why do you encode, decode and do string operations on your IV and key? – Artjom B. Jun 25 '15 at 18:12
  • 2
    Are you aware that CakePHP ships with encrypting functionality? **https://github.com/cakephp/cakephp/blob/2.6.7/lib/Cake/Utility/Security.php#L217**. Also besides the other rather weird stuff, why do you blindly trim on both ends? Are you sure that this doesn't trim away necessary data? – ndm Jun 25 '15 at 18:14
  • The reason for the weird stuff is that this is inherited code under which there are hundreds if not thousands of already encrypted files using this method. Only after adding a new pdf creation of an already existing web form did we notice this. I don't know much about why Cake's encryption scheme is not used but I believe it had something to do with corruption with docx files. – wp4nuv Aug 27 '15 at 15:03
  • Just to clarify, this method works for every other file but the really small ones. – wp4nuv Aug 27 '15 at 15:04

0 Answers0