DEV Community

Cover image for How To Encrypt Fields in Ruby on Rails with Lockbox
Mike Rogers ✈️
Mike Rogers ✈️

Posted on

How To Encrypt Fields in Ruby on Rails with Lockbox

If you're storing any sensitive data such as API Keys, or personal data you should probably be encrypting it within your database. A fantastic gem to do this with is lockbox.

While the best defence against losing sensitive data is to not save it in the first place, you may have a scenerio where you require it later on. From this perspective, it's ideal to make sure you make it as hard for the evil people as possible.

Examples of data you might want to consider encrypting are:

  • API Credentials, for example the tokens you receive from an OAuth request.
  • Email & Postal Address
  • Personally Identifiable Information (PII)

The code

Start by generating a key using Lockbox.generate_key, store the results as the ENV LOCKBOX_MASTER_KEY.

# .env
LOCKBOX_MASTER_KEY="Generate with Lockbox.generate_key"
Enter fullscreen mode Exit fullscreen mode

Create a migration for the field you'd like to encrypt. Once you've decided on the accessor, append _ciphertext to that name.

class AddApiKeyCiphertextToPosts < ActiveRecord::Migration[6.1]
  def change
    add_column :posts, :api_key_ciphertext, :text
  end
end
Enter fullscreen mode Exit fullscreen mode

Lastly, use the encrypts magic within your model to give you a setter & getter which stores its value in that *_ciphertext column as an encrypted value.

# app/models/post.rb
class Post < ApplicationRecord
  # Stored in api_key_ciphertext but encrypted 🤯
  encrypts :api_key
end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)