Created
March 24, 2021 21:11
-
-
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
This file contains hidden or 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' | |
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