Application Key Analyzer
| Analyzer ID | Category | Severity | Time To Fix |
|---|---|---|---|
app-key-security | 🛡️ Security | Critical | 5 minutes |
What This Checks
Validates that Laravel's APP_KEY encryption key is properly configured and secure in your .env file and config/app.php. Checks for:
- Missing or empty APP_KEY in
.env - Placeholder/example values (e.g., "your-key-here")
- Weak key formats (too short or improperly encoded)
- Key size that does not match the cipher in
config/app.php(16 bytes for AES-128, 32 bytes for AES-256) - On Laravel 11 and later,
APP_PREVIOUS_KEYSentries whose size does not match the cipher - Duplicate APP_KEY definitions in
.env, validating the last one, which is the key Laravel reads - Hardcoded keys in
config/app.php(should useenv()) - Insecure cipher algorithms
Why It Matters
- Security Risk: HIGH - The APP_KEY is used for all encryption in Laravel (sessions, cookies, encrypted data)
- Data Loss: If APP_KEY changes, all encrypted data becomes permanently unreadable
- Availability: Laravel's encrypter rejects a key that is not exactly the cipher's size, and from Laravel 11 it checks every key in
APP_PREVIOUS_KEYSthe same way. The cookie encryption middleware resolves the encrypter on every request, so one wrong-size key fails every web request - Session Security: Weak or default keys allow attackers to forge sessions and impersonate users
- CSRF Protection: Laravel's CSRF tokens depend on APP_KEY for cryptographic signing
How to Fix
Quick Fix (1 minute)
Scenario 1: Missing or Empty APP_KEY
# Generate a secure key
php artisan key:generate
# This updates your .env file with a secure base64-encoded key
# APP_KEY=base64:RANDOM_32_BYTE_STRING_HEREScenario 2: Placeholder Value (from .env.example)
# Remove the placeholder and generate a real key
php artisan key:generate --forceScenario 3: Key Size Does Not Match the Cipher
# key:generate writes a key sized for the cipher in config/app.php
php artisan key:generate
# If the cipher was changed after the key was generated, setting
# 'cipher' in config/app.php back to the original keeps existing
# encrypted data readable insteadScenario 4: A Previous Key Does Not Match the Cipher
# Remove the reported entry from APP_PREVIOUS_KEYS in .env.
# Laravel decrypts with the configured cipher for every key, so
# a key generated for another cipher cannot read the data it
# encrypted anyway
# The list is comma-separated with no spaces: a space after a
# comma becomes part of the next key, so it is the wrong size
APP_PREVIOUS_KEYS=base64:FIRST_OLD_KEY,base64:SECOND_OLD_KEYScenario 5: Configuration is Cached
# Clear the cache to allow .env changes to take effect
php artisan config:clear
# After making changes, recache for production
php artisan config:cacheScenario 6: The APP_KEY Line Is Not a Plain APP_KEY= Line
# key:generate only rewrites a line that starts with APP_KEY= followed
# by the current value. On an export, quoted-name or indented line it
# fails with "No APP_KEY variable was found in the .env file", and on
# APP_KEY="" it writes the new key with the quotes still attached
# ❌ Before: key:generate cannot rewrite this line
export APP_KEY="placeholder"
# ✅ After: a plain, unquoted line, then run php artisan key:generate
APP_KEY=Scenario 7: Multiple APP_KEY Definitions
# Laravel reads the last APP_KEY line in .env, so that is the key
# encrypting current sessions, cookies and data: keep it as APP_KEY.
# Data encrypted with an earlier key is unreadable while that key is
# only a duplicate line. On Laravel 11 and later, move the earlier key
# to APP_PREVIOUS_KEYS instead of deleting it, so Laravel can decrypt
# that data again
# ❌ Before: two definitions
APP_KEY=base64:EARLIER_KEY
APP_KEY=base64:KEY_IN_USE
# ✅ After: the key Laravel was reading, and the earlier key kept for decryption
APP_KEY=base64:KEY_IN_USE
APP_PREVIOUS_KEYS=base64:EARLIER_KEYProper Fix (5 minutes)
Implement comprehensive APP_KEY security across all environments:
1. Generate and Store Keys Securely
# Generate key for each environment
php artisan key:generate
# For production, store in environment variables
# Laravel Forge/Vapor:
# - Add APP_KEY to environment variables in dashboard
# Traditional servers:
# - Add to web server environment config
# - Or use encrypted .env files2. Environment-Specific Key Management
# Development (.env) - Use a unique key for local development
APP_KEY=base64:LOCAL_DEV_KEY_HERE
# Production/Staging - Manage through deployment process
# - Use CI/CD environment variables
# - Use secrets managers (AWS Secrets Manager, Vault, etc.)
# - Use platform environment config (Laravel Forge, Vapor, etc.)
# Important: Production and staging should typically use the SAME key
# if you share encrypted data between them (e.g., database backups)3. Never Commit Real Keys to Git
# .env.example - Use placeholders only
APP_NAME=Laravel
APP_ENV=production
APP_KEY=base64:your-key-here
APP_DEBUG=false
APP_URL=https://yourapp.com4. Handle Key Rotation Carefully
On Laravel 11 and later, keep the cipher unchanged and move the old key into APP_PREVIOUS_KEYS when you generate a new one: Laravel then decrypts existing data with the old key. Every previous key must still be the cipher's size. Changing the cipher in the same rotation means APP_PREVIOUS_KEYS cannot read the old data, so re-encrypt it instead, building the old encrypter with the old cipher rather than config('app.cipher').
// If you must rotate keys, decrypt with old key and re-encrypt with new key
// Don't do this unless absolutely necessary (security breach, etc.)
use Illuminate\Support\Facades\Crypt;
use Illuminate\Encryption\Encrypter;
// 1. Backup database first!
// 2. Create encrypter with old key
$oldEncrypter = new Encrypter(
base64_decode(substr('base64:OLD_KEY', 7)),
config('app.cipher')
);
// 3. Decrypt and re-encrypt each encrypted field
$users = DB::table('users')->select('id', 'encrypted_field')->get();
foreach ($users as $user) {
$decrypted = $oldEncrypter->decrypt($user->encrypted_field);
$reencrypted = Crypt::encrypt($decrypted); // Uses new key from config
DB::table('users')
->where('id', $user->id)
->update(['encrypted_field' => $reencrypted]);
}5. Validate Key Format
Ensure your key matches Laravel's expected format and the size of the cipher in config/app.php:
// Valid formats:
// Base64-encoded (recommended - generated by key:generate)
APP_KEY=base64:/AvmHMmBChdiKxwxReS4zWfHKXAfl0vsbJIf2fT3gHA=
// Raw 32-character string (legacy, not recommended)
APP_KEY=SomeRandomStringWith32Characters!
// The key must be exactly the cipher's size (a base64 key is
// measured after decoding):
// 32 bytes for AES-256-CBC and AES-256-GCM (the default cipher)
// 16 bytes for AES-128-CBC and AES-128-GCM
// In an unquoted value, # starts a comment, so APP_KEY= # note is empty6. Production Deployment Checklist
# Before deploying to production:
# 1. Verify APP_KEY is set
php artisan tinker
>>> config('app.key')
// Should output a key, not null
# 2. Verify key length
>>> strlen(base64_decode(substr(config('app.key'), 7)))
// Should be 32 for an AES-256 cipher or 16 for an AES-128 cipher,
// matching config('app.cipher')
# 3. Test encryption/decryption
>>> encrypt('test')
>>> decrypt(encrypt('test'))
// Should return 'test'
# 4. Check cache status
>>> app()->configurationIsCached()
// Should be true in production
# 5. If cached, verify cached key matches .env
cat bootstrap/cache/config.php | grep 'key'ShieldCI Configuration
This analyzer is automatically skipped in CI environments ($runInCI = false).
Why skip in CI?
- CI environments typically use test/placeholder keys for running tests
- Real production keys should never be in the repository or CI environment
- Prevents false failures in CI pipelines where placeholder keys are expected
When to run this analyzer:
- ✅ Local development: Ensures developers have proper keys configured
- ✅ Staging/Production servers: Validates environment-specific keys are secure
- ❌ CI/CD pipelines: Skipped automatically (test keys are expected)
References
- Laravel Encryption Documentation
- Laravel Configuration Documentation
- Artisan key:generate Command
- OWASP Cryptographic Storage Cheat Sheet
Related Analyzers
- Environment File Analyzer - Checks .env file permissions and .gitignore
- Configuration Caching Analyzer - Ensures config is cached in production
- Debug Mode Analyzer - Validates debug mode is disabled in production
- Session Driver Configuration Analyzer - Validates session driver for scalability