Rails uses secret_key_base for encrypting cookies, generating signed and encrypted messages, and verifying the integrity of signed cookies. It's a critical security configuration for any Rails application.
What is Rails SECRET_KEY_BASE?
The secret_key_base in Rails is a 128-character hexadecimal string used as the foundation for the application's key derivation. Rails derives specific keys for different purposes (encryption, signing) from this base key using HKDF.
Key Requirements
- 128 hexadecimal characters (64 bytes)
- Must be kept secret and secure
- Should be unique per application and environment
- Used for cookie encryption, signed messages, and Active Record encryption
How to Use
In Rails 5.2+, use encrypted credentials: ```bash RAILS_MASTER_KEY=your_key rails credentials:edit ``` Or set as an environment variable: ```bash export SECRET_KEY_BASE=your_generated_key_here ``` Generate with Rails: ```bash rails secret ```
Best Practices
- Use Rails credentials (encrypted) for storing secrets
- Keep master.key out of version control
- Use different keys for each environment
- Consider using Rails 7's per-environment credentials
- Back up your master.key securely
Common Mistakes to Avoid
- โCommitting master.key to version control
- โUsing the same secret_key_base across environments
- โNot setting the key in production (falls back to insecure defaults)
- โLosing the master.key (credentials become unreadable)