public
Created

Blowfish encryption wrapper

  • Download Gist
encryption.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.