Skip to content

Instantly share code, notes, and snippets.

@elorest
Last active June 29, 2017 15:28
Show Gist options
  • Save elorest/791b33baa0f24fc84ee8e8120bc2cf49 to your computer and use it in GitHub Desktop.
Save elorest/791b33baa0f24fc84ee8e8120bc2cf49 to your computer and use it in GitHub Desktop.
require "flate"
require "gzip"
require "openssl/cipher"
require "base64"
require "secure_random"
module Flate
def self.write(str)
io = IO::Memory.new
Flate::Writer.new(io) do |flate|
flate.write str.to_slice
end
rstr = io.to_s
io.close
rstr
end
def self.read(str)
io = IO::Memory.new(str.to_slice)
rstr = Flate::Reader.new(io) do |flate|
flate.gets_to_end
end
io.close
rstr
end
end
module Gzip
def self.write(str)
io = IO::Memory.new
Gzip::Writer.open(io) do |gzip|
gzip.write str.to_slice
end
rstr = io.to_s
io.close
rstr
end
def self.read(str)
io = IO::Memory.new(str.to_slice)
rstr = Gzip::Reader.open(io) do |gzip|
gzip.gets_to_end
end
io.close
rstr
end
end
module Enc
def self.encrypt(value, secret = "6f65c214-1b26-46fa-a1c1-3f27ffb13802", alg = "aes-256-cbc", iv = SecureRandom.random_bytes(16))
cipher = OpenSSL::Cipher.new(alg)
cipher.encrypt
cipher.key = secret
cipher.iv = iv
encrypted_data = IO::Memory.new
encrypted_data.write(cipher.update(value.to_slice))
encrypted_data.write(cipher.final)
# "#{::Base64.strict_encode encrypted_data}--#{::Base64.strict_encode iv}"
::Base64.strict_encode encrypted_data
end
def self.decrypt(encrypted_message, secret = "6f65c214-1b26-46fa-a1c1-3f27ffb13802", alg = "aes-256-cbc", iv = SecureRandom.random_bytes(16))
cipher = OpenSSL::Cipher.new(alg)
encrypted_data = ::Base64.decode(encrypted_message)
cipher.decrypt
cipher.key = secret
cipher.iv = iv
decrypted_data = IO::Memory.new
decrypted_data.write cipher.update(encrypted_data)
decrypted_data.write cipher.final
decrypted_data.to_s
end
end
iv = SecureRandom.random_bytes(16)
enc = Enc.encrypt("hey you are now encrypted. That's pretty cool right?", iv: iv)
puts enc
puts Enc.decrypt(enc, iv: iv)
str = Flate.write("We are the world. We are the deflated children.")
puts Flate.read(str)
str2 = Gzip.write("We are the world. We are the gzipped children.")
puts Gzip.read(str2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment