Strongbox

Public Key Encryption for ActiveRecord

View the Project on GitHub spikex/strongbox

Welcome to Strongbox.

Strongbox is a gem which allows ActiveRecord attributes to be automatically encrypted with a public key. Simply put this means anyone can add or update a record, but only someone with the password can read the stored, encrypted data.

Quick Start

Add Strongbox to your Gemfile

gem 'strongbox'

(Strongbox also works with Rails 2.x, you can use the config.gem syntax.)

In your model:

class User < ActiveRecord::Base
  encrypt_with_public_key :secret,
    :key_pair => File.join(RAILS_ROOT,'config','keypair.pem')
end

In your migrations:

class AddSecretColumnsToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :secret, :binary
    add_column :users, :secret_key, :binary
    add_column :users, :secret_iv, :binary
  end
  def self.down
    remove_column :users, :secret
    remove_column :users, :secret_key
    remove_column :users, :secret_iv
  end  
end

Generate a key pair:

(Choose a strong password.)

openssl genrsa -des3 -out config/private.pem 2048
openssl rsa -in config/private.pem -out config/public.pem -outform PEM -pubout
cat config/private.pem  config/public.pem >> config/keypair.pem

In your views and forms you don't need to do anything special to encrypt data:

user = User.new(:secret => 'Shhhhhhhhh....')
user.secret
=> "*encrypted*"

To decrypt call:

user.secret.decrypt 'password'
=> 'Shhhhhhhhh....'