-
Cédric Boutillier authoredCédric Boutillier authored
attr_encrypted
Generates attr_accessors that transparently encrypt and decrypt attributes.
It works with ANY class, however, you get a few extra features when you're using it with ActiveRecord
or Sequel
.
Installation
Add attr_encrypted to your gemfile:
gem "attr_encrypted"
Then install the gem:
bundle install
Usage
If you're using an ORM like ActiveRecord
or Sequel
, using attr_encrypted is easy:
class User
attr_encrypted :ssn, key: 'This is a key that is 256 bits!!'
end
If you're using a PORO, you have to do a little bit more work by extending the class:
class User
extend AttrEncrypted
attr_accessor :name
attr_encrypted :ssn, key: 'This is a key that is 256 bits!!'
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.ssn # returns the unencrypted object ie. '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'
Encrypt/decrypt attribute class methods
Two class methods are available for each attribute: User.encrypt_email
and User.decrypt_email
. They accept as arguments the same options that the attr_encrypted
class method accepts. For example:
key = SecureRandom.random_bytes(32)
iv = SecureRandom.random_bytes(12)
encrypted_email = User.encrypt_email('test@test.com', iv: iv, key: key)
email = User.decrypt_email(encrypted_email, iv: iv, key: key)
The attr_encrypted
class 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 ='(.
attr_encrypted with database persistence
By default, attr_encrypted
uses the :per_attribute_iv
encryption mode. This mode requires a column to store your cipher text and a column to store your IV (initialization vector).