class Slosilo::Symmetric
Constants
- TAG_LENGTH
- VERSION_MAGIC
Public Class Methods
new()
click to toggle source
# File lib/slosilo/symmetric.rb, line 6 def initialize @cipher = OpenSSL::Cipher.new 'aes-256-gcm' # NB: has to be lower case for whatever reason. end
Public Instance Methods
cipher_name()
click to toggle source
This lets us do a final sanity check in migrations from older encryption versions
# File lib/slosilo/symmetric.rb, line 11 def cipher_name @cipher.name end
decrypt(ciphertext, opts = {})
click to toggle source
# File lib/slosilo/symmetric.rb, line 26 def decrypt ciphertext, opts = {} version, tag, iv, ctext = unpack ciphertext raise "Invalid version magic: expected #{VERSION_MAGIC} but was #{version}" unless version == VERSION_MAGIC @cipher.reset @cipher.decrypt @cipher.key = opts[:key] @cipher.iv = iv @cipher.auth_tag = tag @cipher.auth_data = opts[:aad] || "" @cipher.update(ctext) + @cipher.final end
encrypt(plaintext, opts = {})
click to toggle source
# File lib/slosilo/symmetric.rb, line 15 def encrypt plaintext, opts = {} @cipher.reset @cipher.encrypt @cipher.key = (opts[:key] or raise("missing :key option")) @cipher.iv = iv = random_iv @cipher.auth_data = opts[:aad] || "" # Nothing good happens if you set this to nil, or don't set it at all ctext = @cipher.update(plaintext) + @cipher.final tag = @cipher.auth_tag(TAG_LENGTH) "#{VERSION_MAGIC}#{tag}#{iv}#{ctext}" end
random_iv()
click to toggle source
# File lib/slosilo/symmetric.rb, line 40 def random_iv @cipher.random_iv end
random_key()
click to toggle source
# File lib/slosilo/symmetric.rb, line 44 def random_key @cipher.random_key end
Private Instance Methods
unpack(msg)
click to toggle source
return tag, iv, ctext
# File lib/slosilo/symmetric.rb, line 50 def unpack msg msg.unpack "aa#{TAG_LENGTH}a#{@cipher.iv_len}a*" end