Last active
January 28, 2016 22:05
-
-
Save knugie/ef98f3366bbacf806e80 to your computer and use it in GitHub Desktop.
AES - symmetric algorithms for encryption and decryption
This file contains 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' | |
require 'digest/sha2' | |
# Config | |
alg = "AES-256-CBC" | |
# Key | |
key = OpenSSL::Cipher::Cipher.new(alg).random_key | |
# Init Digest | |
digest = Digest::SHA256.new | |
digest.update(key) | |
# initialization vector is not used, because key is random | |
# iv = OpenSSL::Cipher::Cipher.new(alg).random_iv | |
# digest.update(iv) | |
# key64 = [key].pack('m') # Base64 and store the key | |
# key64.unpack('m')[0] # retrieve key from Base64 | |
# raise 'Key Error' if(key.nil? or key.size != 32) | |
# Init encryption Cipher | |
aes = OpenSSL::Cipher::Cipher.new(alg) | |
aes.encrypt | |
aes.key = key | |
# aes.iv = iv # iv is not used | |
# Encode plain text. | |
cipher = aes.update <<PLAIN | |
Classified!! | |
This is a list of all my private data: | |
Item 1 | |
Item 2 | |
Item 3 | |
Item 4 | |
... | |
PLAIN | |
cipher << aes.final | |
# Transmit or store Base64 cipher text | |
cipher64 = [cipher].pack('m') | |
################################################################## | |
# cipher64 and key retrieved | |
# Init decryption Cipher | |
decode_cipher = OpenSSL::Cipher::Cipher.new(alg) | |
decode_cipher.decrypt | |
decode_cipher.key = key | |
# decode_cipher.iv = iv # iv is not used | |
# Decode cipher text | |
plain = decode_cipher.update(cipher64.unpack('m')[0]) | |
plain << decode_cipher.final |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment