Skip to content

Instantly share code, notes, and snippets.

@zaccari
Forked from yukithm/encryption.rb
Created February 27, 2020 06:55
Show Gist options
  • Select an option

  • Save zaccari/2685e26dc8b14c1b61d0d073c30ed353 to your computer and use it in GitHub Desktop.

Select an option

Save zaccari/2685e26dc8b14c1b61d0d073c30ed353 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