How-to Encrypt Ruby on Rails Mail with GnuPG
DRY is a great concept. As one of philosophies upon which Rails is established, Do-Not-Repeat-Yourself is a mantra that is starting to become ever-pervasive in my coding as well as my daily work ethic. So, with that in mind, I’ve decided to NOT respond to the latest email inquiry about how to Encrypt your outgoing email messages from your Rails applications, and just write up a quick tutorial.
I use my GnuPG plugin mainly for e-commerce applications, where secure credit-card storage opens many API integration possibilities with the myriad of Merchant-processor options that are available. It works just as well for any data that necessitates two-way encryption. Lets say you whip up a quick formmail action in rails that emails you live credit card information or top-secret addresses, you’ll wanna provide the rails application with your public key (to properly encrypt the message). Here’s a super-brief overview on how you can do it.
Step 1: Install the plugin
ruby script/plugin install svn://ahgsoftware.com/gnupg/trunk |
Step 2: Generate a mailer
ruby script/generate mailer test_mailer hello_world |
Now we’ve got a TestMailer object with a default hello_world action. Before you move on, remember to add a recipient to the ‘recipient’ field in the model class (otherwise, our test will go nowhere!)
Step 3: Fire up the console
Lets run through the process of loading the gnupg plugin and encrypting a mailout from the console (you can apply this code in your controller at your own discretion).
1 2 3 4 5 6 7 8 9 10 11 12 13 |
## Load GnuPG and the public key of your choice gnupg = GnuPG.new :recipient=>"Key Recipient whomever it may be" gnupg.load_public_key File.read("/path/to/pubkey.asc") ## If its loaded, create the mail, encrypt, send if gnupg.public_key_loaded? email = TestMailer::create_hello_world email.body = gnupg.encrypt(email.body) TestMailer::deliver(email) end ## You probably don't need this, but, for a test, might as well gnupg.drop_public_key |
That should be about it. I’ve used several other methods (including capturing the output buffer and encrypting multi-part mail messages) in a few production sites, and I can’t settle on which method I prefer or where even to place the GnuPG instantiation. Thats what we love about Rails though, a million ways to do anything, and most of them just flow from the code like natural language. I love being a Rubyist. Better than a being a PHPist (masochist?).
July 26th, 2007 at 03:10 AM What about signing mails? Can I do that with your plugin too? Thanks, André