
If you only want to use the credentials on config/credentials.yml.enc, Rails has special methods for that like Rails.application.credentials.
This blog post is for using EncryptedConfiguration with other files.
EncryptedConfiguration
You can use EncryptedConfiguration through Rails.application.encrypted. Let’s say you want to encrypt some data and save the encrypted file on top_secret.txt.enc.
encrypted = Rails.application.encrypted('top_secret.txt.enc')
This will create a new EncryptedConfiguration object which you can use to encrypt and decrypt text.
encrypted.write('This is a top secret message.')
If you check the file top_secret.txt.enc, you will see
EprXfkUXq/rlKQUTPg52OMoSUWfYnPHCiYqxd9y/URvVebmmuhap--QFtMHoVUYleOY8qC--xadtJ2aVQJ2y0IDljt9yAg==
You won’t be able to decrypt this without the key. Notice that we didn’t specify any key when we called Rails.application.encrypted. If you didn’t specify any key, the default master key on config/master.key will be used. This key was created when you created your new Rails 5.2 app. If it doesn’t exist, a key will be created when you run bin/rails credentials:edit.
If you want to use a different key aside from config/master.key, create one by running
ActiveSupport::EncryptedConfiguration.generate_key
You can run this on rails console or from the command line you can run
bundle exec rails runner 'puts ActiveSupport::EncryptedConfiguration.generate_key'
0dbcb53a3e52e6b983bd75d932dca52c
The output is a string with a length of 32. It’s actually a hex as SecureRandom.hex is used.
Save the key to a file. If you use config/top_secret.key as the file name, you can get the EncryptedConfiguration object with
encrypted = Rails.application.encrypted('top_secret.txt.enc', key_path: 'config/top_secret.key')
Then you can write your encrypted text like before.
encrypted.write('This is a top secret message.')
To decrypt the text, run
encrypted.read
=> 'This is a top secret message.'
Currently, there’s no way to open an editor with the decrypted text when using a custom filename. With credentials, you can run bin/rails credentials:edit to open a decrypted version of your credentials from config/credentials.yml.enc.
Conclusion
EncyptedConfiguration is the underlying code that makes credentials work. You don’t need to use it directly but if you have custom needs, give it a try. Rails encourages using it instead of rolling out your own encryption code.