For past week, I have been working on encryption solution for a Rails app.
The requirement was to encrypt chosen fields like
ssn of an ActiveRecord model.
I’ve research a variety of solutions, including attr_encrypted
and encryptor gems.
I want to show a simple way of encryption that combines ActiveRecord::Base.serialize
OpenSSL::Cipher, which comes with the Ruby stdlib.
Few things to bear in mind:
- this kind of encryption helps only in case when your database is stolen
- if hacker gets access to Rails console or
ENV['ENCRYPTION_KEY'], you’re hacked
- you may want to use IV and salt for sensitive data
- by using Marshal, our encrypted field can store instance of any class (Date, Time, whatever!)
Done! You can use
EncryptedCoder in any model.
A quick demo:
Written in December 2015.