2 edited title
| link

PHP: decrypting a file directly to a stream using the defuse Library/PHP_encryption library

source | link

PHP: decrypting a file to a stream using defuse Library

I have for a while been using the excellent Defuse PHP Encryption library for storing encrypted data strings in a database.

I have an extension of this need where I now have files that need to be uploaded and secured at rest. these files are typically no larger than 500Kb documents.

I have been looking into the Defuse / PHP Encryption File class and the system appears to work perfectly for saving newly uploaded files.

However, I'm exploring the best method for opening these encrypted files. The Defuse\Crypto\File class obviously can decrypt the files but it seems to only be able to decrypt them to another, plaintext file.

Is it possible to decrypt the file and output to a string only?

If for instance someone opens an encrypted file, it is decrypted then for as long as they're on that page (the file contents would be viewed/downloaded via a PHP intermediary page so the file location itself is never presented to the user) the plaintext file would be sitting on the server and potentially accessible to anyone who can reach it.

With this in mind I have some queries:

  • Is there any possibility that - Using Defuse PHP Encryption - an encrypted file can be decrypted to a (PHP) stream / string so avoid a plaintext file sitting on the server for any amount of time?

  • I have (just) considered an approach of saving a plaintext file to the server, then using file_get_contents and then unlinking the plaintext file. (This is my preferred approach at the moment but I have only thought of it while writing this question)

    • On Linux servers I believe it would be preferential to overwrite the filedata such as with random_bytes before unlinking the plaintext file. Is this correct?

      My thoughs on this come from unlink only deletes the link to the file and so (potentially) the file may still exist in practise (albeit harder to reach) until the local disk does its usual cleaning up.

  • Is there any advantage -as a concept- to instead loading the plaintext file data from the upload and encrypting that data string with Defuse\Crypto\Crypto and then saving this Crypto encrypted data blob into the storage file?

Research links

I've read the github for the library, and also read the issues and comments surrounding decrypting files to streams but these issues/comments faced more about excessive file sizes, (and the fact the whole file needs to be read). These won't apply in my case.

I have also read a top post from the PHP unlink manual page which seemed to confirm my thoughts on unlink.