Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
L

lockbox

> 数据库
Open source

Modern encryption for Ruby and Rails

1.6K stars0 likes1 views
WebsiteGitHub

About

Modern encryption for Ruby and Rails

Lockbox

:package: Modern encryption for Ruby and Rails

  • Works with database fields, files, and strings
  • Maximizes compatibility with existing code and libraries
  • Makes migrating existing data and key rotation easy
  • Has zero dependencies and many integrations

Learn the principles behind it, how to secure emails with Devise, and how to secure sensitive data in Rails.

Installation

Add this line to your application’s Gemfile:

ruby
gem "lockbox"

Key Generation

Generate a key

ruby
Lockbox.generate_key

Store the key with your other secrets. This is typically Rails credentials or an environment variable (dotenv is great for this). Be sure to use different keys in development and production.

Set the following environment variable with your key (you can use this one in development)

bash
LOCKBOX_MASTER_KEY=0000000000000000000000000000000000000000000000000000000000000000

or add it to your credentials for each environment (rails credentials:edit --environment <env>)

yaml
lockbox:
  master_key: "0000000000000000000000000000000000000000000000000000000000000000"

or create config/initializers/lockbox.rb with something like

ruby
Lockbox.master_key = Rails.application.credentials.lockbox[:master_key]

Then follow the instructions below for the data you want to encrypt.

Database Fields

  • Active Record
  • Action Text
  • Mongoid

Files

  • Active Storage
  • CarrierWave
  • Shrine
  • Local Files

Other

  • Strings

Active Record

Create a migration with:

ruby
class AddEmailCiphertextToUsers < ActiveRecord::Migration[8.1]
  def change
    add_column :users, :email_ciphertext, :text
  end
end

Add to your model:

ruby
class User < ApplicationRecord
  has_encrypted :email
end

You can use email just like any other attribute.

ruby
User.create!(email: "[email protected]")

If you need to query encrypted fields, check out Blind Index.

Multiple Fields

You can specify multiple fields in single line.

ruby
class User < ApplicationRecord
  has_encrypted :email, :phone, :city
end

Types

Fields are strings by default. Specify the type of a field with:

ruby
class User < ApplicationRecord
  has_encrypted :birthday, type: :date
  has_encrypted :signed_at, type: :datetime
  has_encrypted :opens_at, type: :time
  has_encrypted :active, type: :boolean
  has_encrypted :salary, type: :integer
  has_encrypted :latitude, type: :float
  has_encrypted :longitude, type: :decimal
  has_encrypted :video, type: :binary
  has_encrypted :properties, type: :json
  has_encrypted :settings, type: :hash
  has_encrypted :messages, type: :array
  has_encrypted :ip, type: :inet
end

Note: Use a text column for the ciphertext in migrations, regardless of the type

Lockbox automatically works with serialized fields for maximum compatibility with existing code and libraries.

ruby
class User < ApplicationRecord
  serialize :properties, JSON
  store :settings, accessors: [:color, :homepage]
  attribute :configuration, CustomType.new

  has_encrypted :properties, :settings, :configuration
end

For Active Record Store, encrypt the column rather than individual accessors.

For StoreModel, use:

ruby
class User < ApplicationRecord
  has_encrypted :configuration, type: Configuration.to_type

  after_initialize do
    self.configuration ||= {}
  end
end

Validations

Validations work as expected with the exception of uniqueness. Uniqueness validations require a blind index.

Fixtures

You can use encrypted attributes in fixtures with:

yaml
test_user:
  email_ciphertext: <%= User.generate_email_ciphertext("secret").inspect %>

Be sure to include the inspect at the end or it won’t be encoded properly in YAML.

Migrating Existing Data

Lockbox makes it easy to encrypt an existing column without downtime.

Add a new column for the ciphertext, then add to your model:

ruby
class User < ApplicationRecord
  has_encrypted :email, migrating: true
end

Backfill the data in the Rails console:

ruby
Lockbox.migrate(User)

Then update the model to the desired state:

ruby
class User < ApplicationRecord
  has_encrypted :email

  # remove this line after dropping email column
  self.ignored_columns += ["email"]
end

Finally, drop the unencrypted column.

If adding blind indexes, mark them as migrating during this process as well.

ruby
class User < ApplicationRecord
  blind_index :email, migrating: true
end

Model Changes

If tracking changes to model attributes, be sure to remove or redact encrypted attributes.

PaperTrail

ruby
class User < ApplicationRecord
  # for an encrypted history (still tracks ciphertext changes)
  has_paper_trail skip: [:email]

  # for no history (add blind indexes as well)
  has_paper_trail skip: [:email, :email_ciphertext]
end

Audited

ruby
class User < ApplicationRecord
  # for an encrypted history (still tracks ciphertext changes)
  audited except: [:email]

  # for no history (add blind indexes as well)
  audited except: [:email, :email_ciphertext]
end

Decryption

To decrypt data outside the model, use:

ruby
User.decrypt_email_ciphertext(user.email_ciphertext)

Action Text

Note: Action Text uses direct uploads for files, which cannot be encrypted with application-level encryption like Lockbox. This only encrypts the database field.

Create a migration with:

ruby
class AddBodyCiphertextToRichTexts < ActiveRecord::Migration[8.1]
  def change
    add_column :action_text_rich_texts, :body_ciphertext, :text
  end
end

Create config/initializers/lockbox.rb with:

ruby
Lockbox.encrypts_action_text_body(migrating: true)

Migrate existing data:

ruby
Lockbox.migrate(ActionText::RichText)

Update the initializer:

ruby
Lockbox.encrypts_action_text_body

And drop the unencrypted column.

Options

You can pass any Lockbox options to the encrypts_action_text_body method.

Mongoid

Add to your model:

ruby
class User
  field :email_ciphertext, type: String

  has_encrypted :email
end

You can use email just like any other attribute.

ruby
User.create!(email: "[email protected]")

If you need to query encrypted fields, check out Blind Index.

You can migrate existing data similarly to Active Record.

Active Storage

Add to your model:

ruby
class User < ApplicationRecord
  has_one_attached :license
  encrypts_attached :license
end

Works with multiple attachments as well.

ruby
class User < ApplicationRecord
  has_many_attached :documents
  encrypts_attached :documents
end

There are a few limitations to be aware of:

  • Variants and previews aren’t supported when encrypted
  • Metadata like image width and height aren’t extracted when encrypted
  • Direct uploads can’t be encrypted with application-level encryption like Lockbox, but can use server-side encryption

To serve encrypted files, use a controller action.

ruby
def license
  user = User.find(params[:id])
  send_data user.license.download, type: user.license.content_type
end

Use filename to specify a filename or disposition: "inline" to show inline.

Migrating Existing Files

Lockbox makes it easy to encrypt existing files without downtime.

Add to your model:

ruby
class User < ApplicationRecord
  encrypts_attached :license, migrating: true
end

Migrate existing files:

ruby
Lockbox.migrate(User)

Then update the model to the desired state:

ruby
class User < ApplicationRecord
  encrypts_attached :license
end

CarrierWave

Add to your uploader:

ruby
class LicenseUploader < CarrierWave::Uploader::Base
  encrypt
end

Encryption is applied to all versions after processing.

You can mount the uploader as normal. With Active Record, this involves creating a migration:

ruby
class AddLicenseToUsers < ActiveRecord::Migration[8.1]
  def change
    add_column :users, :license, :string
  end
end

And updating the model:

ruby
class User < ApplicationRecord
  mount_uploader :license, LicenseUploader
end

To serve encrypted files, use a controller action.

ruby
def license
  user = User.find(params[:id])
  send_data user.license.read, type: user.license.content_type
end

Use filename to specify a filename or disposition: "inline" to show inline.

Migrating Existing Files

Encrypt existing files without downtime. Create a new encrypted uploader:

ruby
class LicenseV2Uploader < CarrierWave::Uploader::Base
  encrypt key: Lockbox.attribute_key(table: "users", attribute: "license")
end

Add a new column for the uploader, then add to your model:

ruby
class User < ApplicationRecord
  mount_uploader :license_v2, LicenseV2Uploader

  before_save :migrate_license, if: :license_changed?

  def migrate_license
    self.license_v2 = license
  end
end

Migrate existing files:

ruby
User.find_each do |user|
  if user.license? && !user.license_v2?
    user.migrate_license
    user.save!
  end
end

Then update the model to the desired state:

ruby
class User < ApplicationRecord
  mount_uploader :license, LicenseV2Uploader, mount_on: :license_v2
end

Finally, delete the unencrypted files and drop the column for the original uploader. You can also remove the key option from the uploader.

Shrine

Models

Include the attachment as normal:

ruby
class User < ApplicationRecord
  include LicenseUploader::Attachment(:license)
end

And encrypt in a controller (or background job, etc) with:

ruby
license = params.require(:user).fetch(:license)
lockbox = Lockbox.new(key: Lockbox.attribute_key(table: "users", attribute: "license"))
user.license = lockbox.encrypt_io(license)

To serve encrypted files, use a controller action.

ruby
def license
  user = User.find(params[:id])
  lockbox = Lockbox.new(key: Lockbox.attribute_key(table: "users", attribute: "license"))
  send_data lockbox.decrypt(user.license.read), type: user.license.mime_type
end

Use filename to specify a filename or disposition: "inline" to show inline.

Non-Models

Generate a key

ruby
key = Lockbox.generate_key

Create a lockbox

ruby
lockbox = Lockbox.new(key: key)

Encrypt files before passing them to Shrine

ruby
LicenseUploader.upload(lockbox.encrypt_io(file), :store)

And decrypt them after reading

ruby
lockbox.decrypt(uploaded_file.read)

Local Files

Generate a key

ruby
key = Lockbox.generate_key

Create a lockbox

ruby
lockbox = Lockbox.new(key: key)

Encrypt

ruby
ciphertext = lockbox.encrypt(File.binread("file.txt"))

Decrypt

ruby
lockbox.decrypt(ciphertext)

Strings

Generate a key

ruby
key = Lockbox.generate_key

Create a lockbox

ruby
lockbox = Lockbox.new(key: key, encode: true)

Encrypt

ruby
ciphertext = lockbox.encrypt("hello")

Decrypt

ruby
lockbox.decrypt(ciphertext)

Use decrypt_str get the value as UTF-8

Key Rotation

To make key rotation easy, you can pass previous versions of keys that can decrypt.

Create config/initializers/lockbox.rb with:

ruby
Lockbox.default_options[:previous_versions] = [{master_key: previous_key}]

To rotate existing Active Record & Mongoid records, use:

ruby
Lockbox.rotate(User, attributes: [:email])

To rotate existing Act

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rubyactiverecordactivestoragecarrierwaveencryption

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库