-
-
Save pedro108/6aa18f82edd9c1648c56 to your computer and use it in GitHub Desktop.
Ruby class to use the Blowfish encryption / decryption algorithm in a Rails environment. Based on https://gist.github.com/nono/2995118
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
#!/usr/bin/env ruby | |
require 'openssl' | |
class Blowfish | |
def self.key | |
Rails.application.secrets.secret_key_base | |
end | |
def self.encrypt(decrypted_string, salt=nil) | |
decrypted_string += salt unless salt.nil? | |
decrypted_string += ' ' until decrypted_string.bytesize % 8 == 0 | |
cipher = OpenSSL::Cipher.new('bf-ecb').encrypt | |
cipher.padding = 0 | |
cipher.key = key | |
binary_data = (cipher.update(decrypted_string) << cipher.final) | |
binary_data.unpack('H*').first | |
end | |
def self.decrypt(encrypted_string, salt=nil) | |
cipher = OpenSSL::Cipher.new('bf-ecb').decrypt | |
cipher.padding = 0 | |
cipher.key = key | |
binary_data = [encrypted_string].pack('H*') | |
decrypted_string = cipher.update(binary_data) << cipher.final | |
decrypted_string.force_encoding(Encoding::UTF_8) | |
decrypted_string.strip! | |
decrypted_string.gsub! /#{Regexp.quote(salt)}$/, '' unless salt.nil? | |
decrypted_string | |
end | |
end | |
# The encryption key is the Rails secret_key_base | |
bf = Blowfish.new | |
sentence = ARGV[0] || "foo bar foo bar foo bar foo bar foo bar foo bar baz" | |
# Use a salt parameter to enforce security against brute force attacks | |
salt = SecureRandom.hex | |
encrypted = bf.encrypt(sentence, salt) | |
puts encrypted.length | |
puts sentence.inspect | |
puts "Encrypt: #{encrypted}" | |
puts "Decoded: #{bf.decrypt encrypted, salt}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Have you ever tried to run this code?