phpzend-frameworkzend-filter

Zend_Filter_Encrypt and Memory


Is there any way to use Zend_Filter_Encrypt with large files, without rising memory limit to an unacceptable amount?

This is my code so far, but when i have to encrypt files larger than 32 MB (thats my memory limit) it fails, if I set memory to 48MB it works:

$vector = 'XX';

$algorithm = 'rijndael-192';

$options = array(
    'adapter'   => 'mcrypt',
    'vector'    => $vector,
    'algorithm' => $algorithm,
    'key'       => $key
);

$encrypt = new Zend_Filter_File_Encrypt($options);
$result = $encrypt->filter($file);

Solution

  • No, there isn't. Zend_Filter_Encrypt works by encrypting/decrypting the data in one pass, thus requiring the full data in order to function.

    If you need to decrypt a large file, you can do it manually in smaller chunks.

    <?php
    
    $key    = 'secret key';
    $iv     = 'xxxxxxxxxxxxxxxx';
    $cipher = mcrypt_module_open('rijndael-192', '', 'cbc', '');
    
    mcrypt_generic_init($cipher, $key, $iv);
    
    $fp = fopen('/tmp/encrypted.txt', 'r+b');
    while (!feof($fp)) {
        $data = fread($fp, 1154);
    
        $decrypted = mdecrypt_generic($cipher, $data);
    
        echo $decrypted;
    }
    
    fclose($fp);
    mcrypt_generic_deinit($cipher);
    mcrypt_module_close($cipher);
    

    Just make sure the amount of data that you read (fread) is a multiple of the block size used by the algorithm, otherwise the results can be unexpected.