Menü schliessen
Created: May 19th 2025
Categories: Laravel,  Php
Author: Miljan Puzovic

Laravel Encryption Key Rotation

Tags:  Laravel,  Security
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Laravel uses APP_KEY variable defined in tour .env file for encrypting cookies and session cookies. It's recommended to change your APP_KEY at least every six months. But changing the APP_KEY will log out all users. In order to prevent that, there is a new APP_PREVIOUS_KEYS environment variable available from Laravel 11.

Laravel 11 allows you to define your application's previous encryption keys as a comma-delimited list via the APP_PREVIOUS_KEYS environment variable.

Laravel encrypts data using the current encryption key stored in the APP_KEY environment variable. During decryption, Laravel first attempts to use this current key. If unsuccessful, it systematically tries all previous keys until finding one that successfully decrypts the value. This graceful decryption strategy ensures users experience uninterrupted application usage even when encryption keys are rotated.

While this would work for all user sessions out-of-the-box, please keep in mind that if you've used encrypt(), decrypt() or any other Crypt functionalities manually you would need to handle this key change differently. E.g. if you have encrypted your files using encrypt() you would need to decrypt them using the old APP_KEY and encrypt them again using the new one.