Skip to content

Instantly share code, notes, and snippets.

@matrixfox
Forked from smazhara/gist:4740692
Last active October 17, 2015 22:51
Show Gist options
  • Save matrixfox/90728c0c834bbddf3325 to your computer and use it in GitHub Desktop.
Save matrixfox/90728c0c834bbddf3325 to your computer and use it in GitHub Desktop.
Ruby AES128 encrypt-decrypt example
require "openssl"
require "base64"
include Base64
plain_text = "This is the song that never ends, it goes on and on my friends."
cipher = OpenSSL::Cipher::AES128.new(:CBC)
cipher.encrypt
key = cipher.random_key
iv = cipher.random_iv
cipher_text = cipher.update(plain_text) + cipher.final
cipher = OpenSSL::Cipher::AES128.new(:CBC)
cipher.decrypt
cipher.key = key
cipher.iv = iv
decrypted_plain_text = cipher.update(cipher_text) + cipher.final
puts "AES128 in CBC mode"
puts "Key: " + urlsafe_encode64(key)
puts "Iv: " + urlsafe_encode64(iv)
puts "Plain text: " + plain_text
puts "Cipher text: " + urlsafe_encode64(cipher_text)
puts "Decrypted plain text: " + decrypted_plain_text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment