Simple Blowfish encryption with Ruby

I needed to encrypt some text before storing it in the database. Since I needed to get the original back at some point I settled on Blowfish and AES as good candidates. There are a couple gems with provide this type of encryption, but I could not get either one to work.

Eventually I came across this snippet and this blog post. It turns out that it is trivial to use the Ruby OpenSSL library to do encryption. I cleaned up the code from the first snippet a bit:

require 'openssl'

module Blowfish
   def self.cipher(mode, key, data)
     cipher ='bf-cbc').send(mode)
     cipher.key = Digest::SHA256.digest(key)
     cipher.update(data) <<

   def self.encrypt(key, data)
     cipher(:encrypt, key, data)

   def self.decrypt(key, text)
     cipher(:decrypt, key, text)

 if $0 == __FILE__
   p "text" == Blowfish.decrypt("key", Blowfish.encrypt("key", "text"))
Tuesday, July 13, 2010 — 2 notes
  1. fiatdev posted this