How to Encrypt File Uploads with Laravel

• 1 min read

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');

// Get File Content
$fileContent = $file->get();

// Encrypt the Content
$encryptedContent = encrypt($fileContent);

// Store the encrypted Content
Storage::put('file.dat', $encryptedContent);

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

// in your Controller
$encryptedContent = Storage::get('file.dat');
$decryptedContent = decrypt($encryptedContent);

return view('welcome', compact('encryptedContent', 'decryptedContent'));
<!-- welcome.blade.php -->
<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).

// in your Controller
$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.