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 = OpenSSL::Cipher::Cipher.new('bf-cbc').send(mode)
cipher.key = Digest::SHA256.digest(key)
cipher.update(data) << cipher.final
end
def self.encrypt(key, data)
cipher(:encrypt, key, data)
end
def self.decrypt(key, text)
cipher(:decrypt, key, text)
end
end
if $0 == __FILE__
p "text" == Blowfish.decrypt("key", Blowfish.encrypt("key", "text"))
end