Skip to content

Instantly share code, notes, and snippets.

@yukithm
Created July 12, 2016 08:10
Show Gist options
  • Save yukithm/de7fcba1bea8a997554353e556031b51 to your computer and use it in GitHub Desktop.
Save yukithm/de7fcba1bea8a997554353e556031b51 to your computer and use it in GitHub Desktop.
[Ruby] A simple example of AES encryption in Ruby
# encoding: utf-8
require "openssl"
require "base64"
CIPHER_ALGO = "AES-256-CBC"
SALT_SIZE = 8
def encrypt(data, pass)
salt = OpenSSL::Random.random_bytes(SALT_SIZE)
cipher = OpenSSL::Cipher::Cipher.new(CIPHER_ALGO)
cipher.encrypt
cipher.pkcs5_keyivgen(pass, salt, 1)
enc_data = cipher.update(data) + cipher.final
salt + enc_data
end
def decrypt(enc_data, pass)
enc_data = enc_data.dup
enc_data.force_encoding("ASCII-8BIT")
salt = enc_data[0, SALT_SIZE]
data = enc_data[SALT_SIZE..-1]
cipher = OpenSSL::Cipher::Cipher.new(CIPHER_ALGO)
cipher.decrypt
cipher.pkcs5_keyivgen(pass, salt, 1)
cipher.update(data) + cipher.final
end
pass = "foobar"
data = "ひみつ"
enc = encrypt(data, pass)
puts Base64.strict_encode64(enc)
dec = decrypt(enc, pass)
puts dec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment