Skip to content

Instantly share code, notes, and snippets.

@iagopiimenta
Created March 24, 2021 21:11
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 iagopiimenta/1b32dee5ee5a85afd8e9dbbaa2e0d73b to your computer and use it in GitHub Desktop.
Save iagopiimenta/1b32dee5ee5a85afd8e9dbbaa2e0d73b to your computer and use it in GitHub Desktop.
Blowfish Encryption using ECB with short keys compatible with http://sladex.org/blowfish.js/ext/blowfish.js
require 'openssl'
require 'base64'
class Blowfish
def initialize(key, algorithm = 'bf-ecb')
@key = key
@algorithm = algorithm
end
def encrypt(data)
cipher = OpenSSL::Cipher.new(@algorithm)
cipher.encrypt
cipher.key_len = @key.length
cipher.key = @key
binary_data = cipher.update(data)
binary_data << cipher.final
Base64.encode64(binary_data).strip
end
def decrypt(data)
cipher = OpenSSL::Cipher.new(@algorithm)
cipher.decrypt
cipher.key_len = @key.length
cipher.key = @key
data64 = Base64.decode64(data)
binary_data = cipher.update(data64)
binary_data << cipher.final
end
end
data = 'HelLo_WorlD'
crypto = Blowfish.new('TESTKEY')
encrypted_data = crypto.encrypt(data)
decrypted_data = crypto.decrypt(encrypted_data)
p ['encrypted_data', encrypted_data]
p ['decrypted_data', decrypted_data]
p ['valid?', decrypted_data == data]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment