Created
June 10, 2016 11:25
-
-
Save tekacs/a6b036daca20b93578b5fb280f2fd72f to your computer and use it in GitHub Desktop.
Demonstration of using Ruby's OpenSSL module to do symmetric crypto 'correctly'
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
#!/usr/bin/env ruby | |
# tekacs 2k16 | |
require 'digest' | |
require 'openssl' | |
def encrypt(algo, body, key) | |
cipher = OpenSSL::Cipher.new(algo).encrypt | |
cipher.key = key | |
iv = cipher.iv = cipher.random_iv | |
cipher.auth_data = "" if cipher.authenticated? | |
ciphertext = cipher.update(body) + cipher.final | |
tag = cipher.authenticated? ? cipher.auth_tag : "" | |
return ciphertext, iv, tag | |
end | |
def decrypt(algo, body, key, iv, tag = "") | |
cipher = OpenSSL::Cipher.new(algo).decrypt | |
cipher.key = key | |
cipher.iv = iv | |
unless tag.empty? | |
cipher.auth_tag = tag | |
cipher.auth_data = "" | |
end | |
plaintext = cipher.update(body) + cipher.final | |
return plaintext | |
end | |
def key_derivation(password) | |
Digest::SHA256.hexdigest(password) | |
end | |
def to64(bytes) | |
Base64.encode64 bytes | |
end | |
def fr64(string) | |
Base64.decode64 string | |
end | |
ALGO = 'aes-256-gcm' | |
PASS = 'password' | |
ciphertext, iv, tag = encrypt(ALGO, '36', key_derivation(PASS)) | |
puts "ciphertext: #{to64 ciphertext}" | |
puts "iv: #{to64 iv}" | |
puts "tag: #{to64 tag}" | |
# Roundtripping the above values, concatenated, through Base64, is subtle. | |
plaintext = decrypt(ALGO, ciphertext, key_derivation(PASS), iv, tag) | |
puts "plaintext: #{plaintext}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment