Rails: storing encrypted data in database Rails: storing encrypted data in database database database

Rails: storing encrypted data in database


I have gotten attr_encrypted working with Mongo and Mongoid. It takes only a few tweaks.

Make sure that all of the encrypted_ fields that are automatically created by attr_encrypted are explicitly created in the model. For instance, if you have:

    attr_encrypted :email, :key => 'blah blah blah', :encode => true

you need to have:

    field :email, :type => String    field :encrypted_email, :type => String

Also notice you need to tell it to encode the encrypted string otherwise Mongo will complain loudly.

Lastly, if you're encrypting a hash, do this:

    field :raw_auth_hash, :type => Hash    field :encrypted_raw_auth_hash, :type => String    attr_encrypted :raw_auth_hash, :key => 'blah', :marshal => true, :encode => true


I've had a lot of success with the attr_encrypted gem. However, I've only used it with ActiveRecord. I don't know if it works with MongoMapper or Mongoid.

Regardless of how you implement this, I strongly recommend only encrypting certain fields. Don't encrypt every field in every table. Doing that will make it difficult to use associations, search using LIKE, etc.


Try the mongoid-encrypted-fields gem - it is seamless as it handles encryption using mongoize/demongoize methods.

Just define your field like:

field :ssn, type: Mongoid::EncryptedString

Then you can access it like normal, but the data is stored encrypted.