Re-Encrytping Encrypted Fields With A New APP_KEY

Overview


I have one encrypted database field.

The database field is the "websites" database table's "comments" field.

This encryption uses Laravel's "APP_KEY" environment variable.

The problem is that there is no internal facility within Laravel to change this encryption should the "APP_KEY" change. So, I created a custom solution.

I cannot overstate enough that if you make a mistake encrypting data, that data may become unreadable by virtue of not being decrypt-able.

Since this deals with the database, this re-encryption applies to the admin app only.

Warning


I cannot overstate enough that if you make a mistake encrypting data, that data may become unreadable by virtue of not being decrypt-able.

Therefore, treat the key rotation process with the healthy respect that it deserves, given the very real possibility of catastrophy. Brought to you by The Voice Of Experience ™.


BACKUP YOUR DATABASE!

Also, there's the issue of losing your .env file. Do you have your APP_KEY stored somewhere so you can copy it?

APP_KEY Rotation Process


I came up with a step-by-step APP_KEY rotation process, to minimize risk and to make the rotation as convenient as possible. It's still inconvenient, though, because there are manual steps.

The first thing you should do is backup your database! And make sure that that backup actually restores properly to the environment you are using. Do not assume!

php artisan lslibrarybackend:reencryptrunmefirst

This artisan command performs some checks first.

Then, it will ask you to log everyone out of your admin, by logging into the admin (as the "owner") and deleting all the logins records. Deleting your own login record will kick you out of the admin, so you'll be logged-out as well. You don't want anyone doing any CRUD actions to the "websites" database table while you are re-encrypting its "comments" field.

Next, you have to update your .env file. This is what you'll see whilst running the artisan command:


There are three edits to make in the .env file (using a screenshot of .env.example, but you need to edit your .env):

Your excursion with the first of two artisan commands has concluded. The reason for two artisan commands is an artisan command does not recognize changed values in the .env that are changed while that artisan command is running. Your changes to .env will be recognized by a freshly run artisan command, which will be:

php artisan lslibrarybackend:reencryptrunmesecond

This second of two artisan commands is pretty good at nagging, whilst doing some double checking. You will be prompted before this artisan command launches the actual "comments" field re-encryption.

When the re-encryption is done, there is one last step to perform: re-setting the "LASALLE_EMERGENCY_BAN_ALL_USERS_FROM_ADMIN_APP_LOGIN=false" in your .env:

References