Skip to content

Instantly share code, notes, and snippets.

@abriening
Created October 30, 2011 01:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abriening/1325365 to your computer and use it in GitHub Desktop.
Save abriening/1325365 to your computer and use it in GitHub Desktop.
Blowfish encryption wrapper
require 'rubygems'
require 'crypt/blowfish'
require 'base64'
# simple wrapper for blowfish encryption. Assumes all string IO in base64.
module Encryption
extend self
class NilKey < StandardError; end
class InvalidKey < StandardError; end
@@key = nil
@@cypher = nil
def self.key(value=false)
Encryption.validate_key(value == false ? @@key : value)
unless value == false
@@key = value
@@cypher = nil
end
@@key
end
def self.validate_key(value)
raise NilKey, "Set Encryption.encryption_key 'some_key'." if value.nil?
raise InvalidKey, "Bad encryption_key length: the encryption_key must be 1-56 bytes." unless (value.length.between?(1,56))
value
end
def self.cypher
@@cypher ||= Crypt::Blowfish.new(Encryption.key)
end
def encrypt_string str
Base64.encode64( Encryption.cypher.encrypt_string(str) )
end
def decrypt_string str
Encryption.cypher.decrypt_string( Base64.decode64(str) )
end
def encrypt_file( plain_file_name, crypted_output_file_name )
Encryption.cypher.encrypt_file(plain_file_name, crypted_output_file_name)
end
def decrypt_file( crypted_file_name, plain_output_file_name )
Encryption.cypher.decrypt_file(crypted_file_name, plain_output_file_name)
end
end
if __FILE__ == $0
require 'test/unit'
class TestEncryptionModule < Test::Unit::TestCase
def test_nil_key_raised
assert_raise Encryption::NilKey do
Encryption.key nil
end
end
def test_invalid_key_raised
assert_raise Encryption::InvalidKey do
Encryption.key ""
end
assert_raise Encryption::InvalidKey do
Encryption.key("x" * 57)
end
end
def test_encrypt_and_decrypt_string
Encryption.key 'some_key'
plain = "this is some text"
crypted = Encryption.encrypt_string plain
assert plain != crypted
assert_equal plain, Encryption.decrypt_string(crypted)
end
def test_changing_key
plain = "this is some text"
Encryption.key 'some_key'
crypted = Encryption.encrypt_string plain
Encryption.key "a_different_key"
other_crypted = Encryption.encrypt_string plain
assert_equal plain, Encryption.decrypt_string(other_crypted)
Encryption.key 'some_key'
assert_equal plain, Encryption.decrypt_string(crypted)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment