What is the Crypt facade
Laravel’s encryption service provides a simple interface for encrypting and decrypting values using OpenSSL with AES-256-CBC (or AES-128-CBC). All values encrypted by Laravel are signed with a message authentication code (MAC). This ensures that any tampering with the encrypted value will prevent it from being decrypted.Configuration
Generating the APP_KEY
Before using encryption, you need to set thekey value in config/app.php.
This value is loaded from the APP_KEY environment variable.
Use the php artisan key:generate command to generate a secure key.
It generates a cryptographically secure key using PHP’s secure random number generator.
.env file.
Rotating the encryption key
When you change the encryption key, all authenticated user sessions are logged out. This is because Laravel encrypts all cookies, including session cookies. Also, data encrypted with the previous key can no longer be decrypted. To mitigate this, you can list old keys separated by commas inAPP_PREVIOUS_KEYS.
Encryption
Use theencryptString method on the Crypt facade to encrypt a value.
The encrypted value uses OpenSSL with AES-256-CBC and is signed with a MAC.
Decryption
Use thedecryptString method on the Crypt facade to decrypt an encrypted value.
If decryption fails (for example, if the MAC is invalid), a DecryptException is thrown.
Model casts
Using theencrypted cast on an Eloquent model, an attribute is automatically encrypted and decrypted.
The
encrypted:* casts internally use Crypt::encrypt and Crypt::decrypt.
A text or longText database column type is recommended.Practical example: encrypting personal information
A typical pattern for securely storing personal information (national ID numbers, credit card numbers, etc.) in the database.Migration
Model
Controller
Summary
Next steps
Hashing
Learn how to securely hash and verify passwords.
Authorization
Learn about access control using policies and gates.