Skip to content

Instantly share code, notes, and snippets.

@pedro108
Forked from nono/blowfish.rb
Last active May 27, 2020 02:04
Show Gist options
  • Save pedro108/6aa18f82edd9c1648c56 to your computer and use it in GitHub Desktop.
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
#!/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}"
@armansa
Copy link

armansa commented May 27, 2020

Have you ever tried to run this code?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment