Acts As Encryptable¶ ↑
While other encryption libraries require a separate column for each encrypted field, ActsAsEncryptable requires only one extra column per table. It works by mashing the fields to be encrypted into a YAML string and then breaking that into bite-sized chunks which are individually encrypted and munged together into an undecipherable string that is then stored in the database.
Encryption and decryption is done with asymmetric keys using Ruby’s OpenSSL libraries. While sample keys are provided for testing and development, it is highly recommended that you provide your own key pair for production use. The cryptographic library that comes with the gem can be used to generate them. Be sure to store your private key in a secure place as your data is only safe so long as your private key remains so.
Installation¶ ↑
Run this if the gem isn’t installed already
gem install ssoper-acts_as_encryptable --source=http://gems.github.com
Or place in your environment.rb
config.gem 'ssoper-acts_as_encryptable', :lib => 'acts_as_encryptable', :source => 'http://gems.github.com'
Configuration¶ ↑
After installing be sure to add a column to any tables that need to be encrypted
class AddEncryptionFieldsToCreditCards < ActiveRecord::Migration def self.up add_column :credit_cards, :encrypted, :text end def self.down remove_column :credit_cards, :encrypted end end
Or you can use the migration helper to generate the migration for the model
./script/generate acts_as_encryptable_migration credit_cards
In your model you will setup the virtual attributes to be encrypted and pass them to acts_as_encryptable
class CreditCard < ActiveRecord::Base attr_accessor :first_name, :last_name, :number acts_as_encryptable :first_name, :last_name, :number end
Usage¶ ↑
Encrypt your data
card = CreditCard.new card.first_name = 'Test' card.last_name = 'User' card.number = '1234567890' card.save
Decrypt your data
card = CreditCard.last card.decrypt! => { :first_name => 'Test', :last_name => 'User', :number => '1234567890' }
Tests¶ ↑
The gem comes with unit tests that use SQLite files stored in /tmp. You can run them with the test task.
rake test
Acknowledgements¶ ↑
-
Paul Barry for helping simplify the functionality
-
Tobias Lütke for his blog post on asymmetric encryption using Ruby’s native SSL libraries
Contact¶ ↑
Feel free to contact me at sean.soper@gmail.com