Encrypted application configuration

If you want to automate a process that requires a lot of sensitive information—passwords, a PIN, the second, πth and eleventy-first letters of your so-called ‘memorable word’, and so on—then you probably don’t want to type all of them in separately every time. On the other hand, you probably also don’t want them to be stored in plain text on your computer, even if you’re using full-disk encryption.

It’s easy to encrypt the configuration securely so that you only need one password when running the program. I’ll show you how to do it in Ruby using AES256 encryption and JSON as the configuration file format as an example. All you need is GnuPG installed and available in your path, and to have generated a keypair. (This is optional: see the end for how to use symmetric encryption instead of a keypair.)

To generate the configuration file, run (using the email address corresponding to your key):

$ gpg --encrypt --cipher-algo aes256 \
--recipient you@example.com --output config.json.gpg -

and type (or more likely paste) your JSON configuration and press Ctrl-D.

In your application, you can read the configuration using:

config = JSON.parse(%x{ gpg --decrypt config.json.gpg })

You’ll be prompted to enter your secret key’s password. Depending on your environment, this may be a GUI dialog box or a shell prompt. If you’re using an agent, your system may remember this password for a time.

Handling the failure case is left to the reader, but that should be enough to get started.

If you don’t want to deal with a keypair, you can generate the configuration file using symmetric encryption instead:

$ gpg --symmetric --cipher-algo aes256 \
--output config.json.gpg

Decryption is the same regardless of the encryption method.