Module: JWA::Algorithms::ContentEncryption::AesGcm

Included in:
A128Gcm, A192Gcm, A256Gcm
Defined in:
lib/jwa/algorithms/content_encryption/aes_gcm.rb

Overview

Abstract AES in Galois Counter mode for different key sizes.

Defined Under Namespace

Modules: ClassMethods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#ivObject (readonly)

Returns the value of attribute iv.



8
9
10
# File 'lib/jwa/algorithms/content_encryption/aes_gcm.rb', line 8

def iv
  @iv
end

#keyObject (readonly)

Returns the value of attribute key.



8
9
10
# File 'lib/jwa/algorithms/content_encryption/aes_gcm.rb', line 8

def key
  @key
end

Class Method Details

.included(base) ⇒ Object



49
50
51
# File 'lib/jwa/algorithms/content_encryption/aes_gcm.rb', line 49

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#cipherObject



45
46
47
# 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) ⇒ Object



30
31
32
33
34
35
# 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) ⇒ Object



23
24
25
26
27
28
# 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

#initialize(key, iv = nil) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
# 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

#setup_cipher(direction, auth_data, tag = nil) ⇒ Object



37
38
39
40
41
42
43
# 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