Created
May 31, 2013 16:11
-
-
Save kajic/5686064 to your computer and use it in GitHub Desktop.
Blowfish encryption and decryption of strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'openssl' | |
require 'base64' | |
module Cipher | |
def self.encrypt(key, data) | |
data += 'A' # Add 'A' suffix to support empty data | |
cipher(:encrypt, key, data) | |
end | |
def self.decrypt(key, text) | |
data = cipher(:decrypt, key, text) | |
data[0...-1] # Remove the 'A' suffix | |
end | |
def self.encrypt_base64(key, data) | |
blowfish_string = self.encrypt(key, data) | |
Base64.encode64(blowfish_string) | |
end | |
def self.decrypt_base64(key, base64_string) | |
blowfish_string = Base64.decode64(base64_string) | |
self.decrypt(key, blowfish_string) | |
end | |
private | |
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 | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'spec_helper' | |
describe Cipher do | |
let(:key) { 'secret key' } | |
describe 'blowfish' do | |
it 'encodes and decodes empty strings' do | |
original = '' | |
encrypted = Cipher.encrypt(key, original) | |
decrypted = Cipher.decrypt(key, encrypted) | |
decrypted.should == original | |
end | |
it 'encodes and decodes strings' do | |
original = 'my string' | |
encrypted = Cipher.encrypt(key, original) | |
decrypted = Cipher.decrypt(key, encrypted) | |
decrypted.should == original | |
end | |
end | |
describe 'base64 and blowfish' do | |
it 'encodes and decodes empty strings' do | |
original = '' | |
encrypted = Cipher.encrypt_base64(key, original) | |
decrypted = Cipher.decrypt_base64(key, encrypted) | |
decrypted.should == original | |
end | |
it 'encodes and decodes strings' do | |
original = 'my string' | |
encrypted = Cipher.encrypt_base64(key, original) | |
decrypted = Cipher.decrypt_base64(key, encrypted) | |
decrypted.should == original | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
updated spec for newer rspec syntax