Rails 7 Credentials Setup Link to heading

Rails 7 by default has credentials created during setup. The credentials file is place in the config/ directory and is encrypted. The master key for the file can also be found in the config/ directory.

The files are credentials.yml.enc and master.key. The master.key file should not be committed to git or any form of version control.

Creating a credentials file Link to heading

If you don’t have the file already created or you have lost the master key, you can re-create the file. Any credentials already stored in the old file will be lost.

The command to create or edit the file is the same:

bin/rails credentials:edit

Adding an RSA Key pair Link to heading

RSA keys can be generated using the openssl command or in the IRB or Rails console.

Generating with OpenSSL Link to heading

# Generate the key
openssl genpkey -algorithm RSA -out private_key.pem -pkeyopt rsa_keygen_bits:2048

# Extract the public key
openssl rsa -pubout -in private_key.pem -out public_key.pem

Generating with IRB Link to heading

require "openssl"

# Create the key
key = OpenSSL::PKey::RSA.new(2048)

# Export the private key to pem
key.private_to_pem

# Export the public key to pem
key.public_to_pem

Updating the values in credentials.yml.enc Link to heading

Base64 encode the keys and store them in credentials.yml.enc either from Rails console or from an editor of your choice.

EDITOR=nvim bin/rails credentials:edit

Once the editor is closed, the keys will be encrypted in the credentials file. Remember to commit the credentials.yml.enc file so that the key is available in Rails everywhere else. The master.key should only be shared via a secrets manager or some such.

References Link to heading