module JWA::Algorithms::ContentEncryption::AesGcm
Abstract AES in Galois Counter mode for different key sizes.
Attributes
iv[R]
key[R]
Public Class Methods
included(base)
click to toggle source
# File lib/jwa/algorithms/content_encryption/aes_gcm.rb, line 49 def self.included(base) base.extend(ClassMethods) end
new(key, iv = nil)
click to toggle source
# File lib/jwa/algorithms/content_encryption/aes_gcm.rb, line 10 def initialize(key, iv = nil) @key = key @iv = iv || SecureRandom.random_bytes(12) if @key.length != self.class.key_length raise ArgumentError, "Invalid Key. Expected length: #{self.class.key_length}. Actual: #{@key.length}." end if @iv.length != 12 raise ArgumentError, "Invalid IV. Expected length: 12. Actual: #{@iv.length}." end end
Public Instance Methods
cipher()
click to toggle source
# File lib/jwa/algorithms/content_encryption/aes_gcm.rb, line 45 def cipher @cipher ||= Cipher.for(self.class.cipher_name) end
decrypt(ciphertext, authenticated_data, tag)
click to toggle source
# File lib/jwa/algorithms/content_encryption/aes_gcm.rb, line 30 def decrypt(ciphertext, authenticated_data, tag) setup_cipher(:decrypt, authenticated_data, tag) cipher.update(ciphertext) + cipher.final rescue OpenSSL::Cipher::CipherError raise JWA::BadDecrypt, 'Invalid ciphertext or authentication tag' end
encrypt(plaintext, authenticated_data)
click to toggle source
# File lib/jwa/algorithms/content_encryption/aes_gcm.rb, line 23 def encrypt(plaintext, authenticated_data) setup_cipher(:encrypt, authenticated_data) ciphertext = cipher.update(plaintext) + cipher.final [ciphertext, cipher.auth_tag] end
setup_cipher(direction, auth_data, tag = nil)
click to toggle source
# File lib/jwa/algorithms/content_encryption/aes_gcm.rb, line 37 def setup_cipher(direction, auth_data, tag = nil) cipher.send(direction) cipher.key = @key cipher.iv = @iv cipher.auth_tag = tag if tag cipher.auth_data = auth_data end