Some information might be out of date, as I don't always update older articles.

I always thought file encryption in Laravel is complex, but as it turns out, it's really easy.

Here's the code you could use in your controller to encrypt an uploaded file.

$file = $request->file( 'attachment' ); $fileContent = $file->get(); $encryptedContent = encrypt($fileContent); Storage::put( 'file.dat' , $encryptedContent);

And here's the code you could use to display the uploaded image in your views:

$encryptedContent = Storage::get( 'file.dat' ); $decryptedContent = decrypt($encryptedContent); return view( 'welcome' , compact( 'encryptedContent' , 'decryptedContent' ));

< img src = "data:image/png;base64,{!! base64_encode($decryptedContent) !!}" alt = "" />

It's also possible to attach a file as a stream to a controller response (allows users to download the decrypted file).

$encryptedContent = Storage::get( 'file.dat' ); $decryptedContent = decrypt($encryptedContent); return response()->streamDownload( function () use ($decryptedContent) { echo $decryptedContent; }, 'file.jpg' );

The encrypted file is stored in a file with the .dat -extension. DAT files usually contain generic data which is only accessed by the application and not by users.

I've published a demo project on GitHub where you can start tinkering with the code immediately. Just follow the installation instructions in the README.

If you want to see a real world application using this technique, check out Firefly III (code example) an open source finance manager built with Laravel.