Last active
May 23, 2021 13:50
-
-
Save faustinoaq/c10e3e37d4d1a21cf13118a07920190f to your computer and use it in GitHub Desktop.
AES Cipher example in Crystal
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/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") |
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
Thanks. Good reference.