Announcement: sql_crypt plugin for Rails

by Mechaferret on October 24th, 2009

I’ve just released an open source plugin for Rails called sql_crypt, available at

This plugin provides two-way encryption of ActiveRecord attributes in a database using database encryption functions, instead of encrypting in code. This is useful when you are encrypting large numbers of model objects at once, for which Ruby encryption can be too slow, or if other applications written in languages besides Ruby are accessing the encrypted attributes, which would require keeping multiple implementations of the encryption algorithm synchronized.


Using sql_crypt is very simple. The following example will encrypt the “balance” attribute of an Account model:

class Account < ActiveRecord::Base
  sql_encrypted :balance, :key => 'my_secret_key'

You can specify multiple fields on the same line if they are using the same key; use separate lines for different keys, e.g.

  sql_encrypted :cc_number, :ssn, :key => 'fIn^nce-dan{}er'
  sql_encrypted :password, :key => 'password'

will encrypt “cc_number” and “ssn” using the key ‘fIn^nce-dan{}er’ and “password” using the key ‘password’.


I was working on a payroll application, which obviously needed to have two-way encryption for many different fields: salary, bonuses, reimbursements. The application has a summary page that would fetch data for all employees and display it on a single page. Originally, I implemented the encryption in Ruby using the crypt gem, but with over 100 employees the summary page was getting very slow to load. Thus, I switched to using MySQL’s aes_encrypt/aes_decrypt, which fixed that problem. Since I had many different attributes that needed encryption, it made sense to create a class method to specify that an attribute would be encrypted, and thus the code for sql_crypt was initially written.

Later, we had two separate applications that were accessing two-way encrypted fields using both Rails and PHP, and we were having some trouble getting the MD5 implementations to match. Reusing the sql_crypt code from the payroll app was the obvious solution. Once that was done, the code was general enough that, with a few tweaks, it seemed like it might be made useful for the general community. I made the tweaks, and sql_crypt is now publicly available.

All comments and suggestions are welcome.

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS