Skip to content

Instantly share code, notes, and snippets.

@faustinoaq
Last active May 23, 2021 13:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save faustinoaq/c10e3e37d4d1a21cf13118a07920190f to your computer and use it in GitHub Desktop.
Save faustinoaq/c10e3e37d4d1a21cf13118a07920190f to your computer and use it in GitHub Desktop.
AES Cipher example in Crystal
require "openssl/cipher"
module AES
def self.encrypt(data, password)
cipher = OpenSSL::Cipher.new("aes-128-cbc")
cipher.encrypt
cipher.key = password
io = IO::Memory.new
io.write(cipher.update(data))
io.write(cipher.final)
io.to_slice
end
def self.decrypt(data, password)
cipher = OpenSSL::Cipher.new("aes-128-cbc")
cipher.decrypt
cipher.key = password
io = IO::Memory.new
io.write(cipher.update(data))
io.write(cipher.final)
io.to_s
end
end
encrypted = AES.encrypt("my awesome data", "my awesome password")
pp AES.decrypt(encrypted, "my awesome password")
@Naoyo
Copy link

Naoyo commented Jan 13, 2019

Thanks. Good reference.

@mqu
Copy link

mqu commented May 23, 2021

Thank you so much. Works also with AES-CBC-256.

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