Skip to content

Instantly share code, notes, and snippets.

@tekacs
Created June 10, 2016 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tekacs/a6b036daca20b93578b5fb280f2fd72f to your computer and use it in GitHub Desktop.
Save tekacs/a6b036daca20b93578b5fb280f2fd72f to your computer and use it in GitHub Desktop.
Demonstration of using Ruby's OpenSSL module to do symmetric crypto 'correctly'
#!/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