Skip to content

Instantly share code, notes, and snippets.

@deevis
Last active July 17, 2019 21:40
Show Gist options
  • Save deevis/d30fb96dfc5bbdf94d1fd8e34f077ef8 to your computer and use it in GitHub Desktop.
Save deevis/d30fb96dfc5bbdf94d1fd8e34f077ef8 to your computer and use it in GitHub Desktop.
Ruby AES Cryptography
require 'openssl'
require 'stringio'
require 'base64'
class Cryptomancer
def initialize(alg: nil, key: nil)
@alg = alg || "AES-256-CBC"
@key = key || "1234567890123456ASDFasdfASDFasdf" # 32 byte key for 256-bit AES (16 bytes for 128-bit...)
end
def encrypt(str)
aes = OpenSSL::Cipher.new(@alg)
aes.encrypt
aes.key = @key
aes.random_iv
enc = ""
f = StringIO.new(str)
loop do
r = f.read(4096)
break unless r
cipher = aes.update(r)
enc += cipher
end
enc += aes.final
return Base64.encode64(enc)
end
def decrypt(data)
bytes = Base64.decode64(data)
aes = OpenSSL::Cipher.new(@alg)
aes.decrypt
aes.key = @key
aes.update(bytes)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment