How to Encrypt File Uploads with Laravel
This article has been published a while ago.
If this is a technical article some information might be out of date. If something is terribly broken, let me know and I will update the article accordingly.
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.