Search code examples
phpcakephpmcryptrijndaelcbc-mode

How to calculate output length for PHP Mcrypt Rijndael 256 CBC


I want to use a plug-in for cakephp to store encrypted data in the database. But I want to calculate how much length is necessary for database fields.

Here is the encryption code of the plugin:

return base64_encode(
     mcrypt_encrypt(
          MCRYPT_RIJNDAEL_256, md5($settings['key']
     ), $value, MCRYPT_MODE_CBC, md5(md5($settings['key']
))));

For instance how much field length is necessary for 2000 lengthed raw string input? VARCHAR(?)

If you need more details here is the All Plug-in Code:

https://github.com/jmillerdesign/Cipher-Behavior-for-CakePHP/blob/master/Model/Behavior/CipherBehavior.php


Solution

  • I think the estimated answer is, source string length + 35% (of source str length).

    I did a test like this to find the answer:

    $key = 'really long key hello world';
    
    // Source String
    $str = '';
    for ($i = 1; $i <= 2000; $i++) {
        $str .=  'x';
    }
    $slength = strlen($str);
    echo 'source str length = '. $slength."<br>";
    $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $str, MCRYPT_MODE_ECB));
    
    $elength = strlen($encrypted);
    echo 'encrypted str length = '. $elength."<br>";
    
    echo 'diff = '. (($elength - $slength)/$slength) * 100 .'%';
    

    Outputs:

    source str length = 2000
    encrypted str length = 2688
    diff = 34.4%
    
    
    source str length = 20000
    encrypted str length = 26668
    diff = 33.34%
    

    Instead of using a fixed varchar, why don't you use the field type text?