Created
June 18, 2014 22:00
-
-
Save zuazo/538d0edca72603996106 to your computer and use it in GitHub Desktop.
Checks aead gem compatibility with OpenSSL core in ruby >= 2
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
# Requires Ruby >= 2 | |
require "openssl" | |
require "aead" | |
key = Digest::SHA256.digest("key") # digest_length 32 | |
algorithm = "aes-256-gcm" | |
data = "plaintext data" | |
auth_data = "authentication data" | |
puts "Encryption using OpenSSL" | |
cipher = OpenSSL::Cipher.new(algorithm) # key len 32 | |
cipher.encrypt | |
cipher.key = key | |
cipher.iv = iv = cipher.random_iv | |
cipher.auth_data = auth_data | |
enc_data = cipher.update(data) + cipher.final | |
tag = cipher.auth_tag | |
puts " enc_data length: #{enc_data.length}" | |
puts " iv length: #{iv.length}" | |
puts " tag length: #{tag.length}" | |
puts "\nDecryption using AEAD" | |
mode = AEAD::Cipher.new(algorithm) | |
cipher = mode.new(key) | |
ciphertext = enc_data + tag | |
plaintext = cipher.decrypt(iv, auth_data, ciphertext) | |
puts " plaintext: #{plaintext}" | |
puts "\nEncryption using AEAD" | |
mode = AEAD::Cipher.new(algorithm) | |
key = mode.generate_key | |
iv = mode.generate_nonce | |
cipher = mode.new(key) | |
ciphertext = cipher.encrypt(iv, auth_data, data) | |
tag = ciphertext[ -cipher.class.tag_len .. -1 ].to_s | |
enc_data = ciphertext[ 0 .. -cipher.class.tag_len - 1 ].to_s | |
puts " enc_data length: #{enc_data.length}" | |
puts " iv length: #{iv.length}" | |
puts " tag length: #{tag.length}" | |
puts "\nDecryption using OpenSSL" | |
decipher = OpenSSL::Cipher.new(algorithm) | |
decipher.decrypt | |
decipher.key = key | |
decipher.iv = iv | |
decipher.auth_data = auth_data | |
decipher.auth_tag = tag | |
plaintext = decipher.update(enc_data) + decipher.final | |
puts " plaintext: #{plaintext}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment