Skip to content

Instantly share code, notes, and snippets.

@cluesque
Created December 20, 2016 03:18
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 cluesque/df4054793c90f9637b43f918fe64db34 to your computer and use it in GitHub Desktop.
Save cluesque/df4054793c90f9637b43f918fe64db34 to your computer and use it in GitHub Desktop.
Toy class demonstrating encryption and decryption with aes-256-gcm
class Cryptor
# Usage:
# cipher = Cryptor.new(key, auth_data: '1234').encrypt(clear)
# clear = Cryptor.new(key, auth_data: '12344').decrypt(cipher)
attr_accessor :key, :auth_data
# The auth_data should be something different for each text, perhaps a database row id?
def initialize(key, auth_data: 'aad')
self.mode = mode
self.key = key
self.auth_data = auth_data
end
def encrypt(text)
aes = OpenSSL::Cipher.new(mode)
aes.encrypt
aes.key = key
iv = aes.random_iv
aes.auth_data = auth_data
iv + aes.update(text) + aes.final + aes.auth_tag
end
def decrypt(cypher)
aes = OpenSSL::Cipher.new(mode)
aes.decrypt
aes.key = key
aes.iv = cypher[0..iv_length-1]
aes.auth_data = auth_data
aes.auth_tag = cypher[-(tag_length)..-1]
aes.update(cypher[iv_length..-(tag_length+1)]) + aes.final
end
private
# The two lengths are a function of the mode.
def mode
'aes-256-gcm'
end
def iv_length
12
end
def tag_length
16
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment