Option 1. Use something like this (GitHub Laravel Encryptenv).
Your mileage may vary, as it's not exactly easy to maintain and setup.
Option 2. Cook a variation of the above (but a lot more simple). In your config/database.php file:
use Illuminate\Encryption\Encrypter;
$key = getenv('SECRETKEY');
$encrypter = new Encrypter($key, 'aes-128-cbc');
//...
'mysql' => [
//...
'password' => $encrypter->decrypt(env('DB_PASSWORD', '')),
Obviously, SECRETKEY is an environment variable holding the decryption key.
You may ask "Where would I get the decryption key SECRETKEY from?"
One option is to inject it via your web server, for example in your nginx config, within sites-enabled/001-yoursite.conf configuration:
location ~ \.php$ {
set $script_filename $document_root$fastcgi_script_name;
set $configkey "";
if ($script_filename = "/var/www/yoursitepath/html/public/index.php") {
set $configkey "AAAAAAAAAAAAAAAA";
}
fastcgi_param SCRIPT_FILENAME $script_filename;
fastcgi_param CONFIGKEY $configkey;
where "AAAAAAAAAAAAAAAAA" is your AES-128-CBC key (has to be 16 characters). Feel free to switch to AES-256-CBC, if you want a larger key (and a bit more questionable security).
The above provides the key only to your Laravel index.php file. The reason for this restriction is that anyone that can create a PHP file in your webroot would be able to just print the value of the key, so your entire house of cards will collapse.
For the above to have any meaningful protection:
- You must restrict the nginx config file 001-yoursite.conf to be readable only by root.
- You must disable anyone from modifying index.php (chmod 440 index.php). If you allow regular system users to modify your index.php, they would be able to trivially print out your "secret key".
The above "encryption" protects only against stuff like shoulder-surfing attacks, and is by no means a replacement for proper security measures, such as careful configuration of your webroot, hardening, etc.
The above mainly works for scenarios where you need to make compliance beancounters happy.
.env
files are usually not available via your webserver/publicly viewable.env
file gets compromised (spoiler: it's bad) and since the APP_KEY used to encrypt and decrypt data is save there too I would say it's not worth the hassle.