Created
December 20, 2016 03:18
-
-
Save cluesque/df4054793c90f9637b43f918fe64db34 to your computer and use it in GitHub Desktop.
Toy class demonstrating encryption and decryption with aes-256-gcm
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
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