Generates attr_accessors that encrypt and decrypt attributes transparently
It works with ANY class, however, you get a few extra features when you’re using it with ActiveRecord
, DataMapper
, or Sequel
gem install attr_encrypted
Encrypting attributes has never been easier:
class User attr_accessor :name attr_encrypted :ssn, :key => 'a secret key' def load # loads the stored data end def save # saves the :name and :encrypted_ssn attributes somewhere (e.g. filesystem, database, etc) end end @user = User.new @user.ssn = '123-45-6789' @user.encrypted_ssn # returns the encrypted version of :ssn @user.save @user = User.load @user.ssn # decrypts :encrypted_ssn and returns '123-45-6789'
The attr_encrypted
method is also aliased as attr_encryptor
to conform to Ruby’s attr_
naming conventions. I should have called this project attr_encryptor
but it was too late when I realized it =‘(.
By default, the encrypted attribute name is encrypted_#{attribute}
(e.g. attr_encrypted :email
would create an attribute named encrypted_email
). So, if you’re storing the encrypted attribute in the database, you need to make sure the encrypted_#{attribute}
field exists in your table. You have a couple of options if you want to name your attribute something else.
You can simply pass the name of the encrypted attribute as the :attribute
option:
class User attr_encrypted :email, :key => 'a secret key', :attribute => 'email_encrypted' end
This would generate an attribute named email_encrypted
If you’re planning on encrypting a few different attributes and you don’t like the encrypted_#{attribute}
naming convention then you can specify your own:
class User attr_encrypted :email, :credit_card, :ssn, :key => 'a secret key', :prefix => 'secret_', :suffix => '_crypted' end
This would generate the following attributes: secret_email_crypted
, secret_credit_card_crypted
, and secret_ssn_crypted
.
Although a :key
option may not be required (see custom encryptor below), it has a few special features