Class: Sandal::Enc::AGCM

Inherits:
Object
  • Object
show all
Defined in:
lib/sandal/enc/agcm.rb

Overview

Base implementation of the A*GCM family of encryption methods.

Direct Known Subclasses

A128GCM, A256GCM

Constant Summary collapse

@@iv_size =
96
@@auth_tag_size =
128

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, aes_size, alg) ⇒ AGCM

Initialises a new instance; it’s probably easier to use one of the subclass constructors.

Parameters:

  • aes_size (Integer)

    The size of the AES algorithm, in bits.

  • alg (#name, #encrypt_key, #decrypt_key)

    The algorithm to use to encrypt and/or decrypt the AES key.



23
24
25
26
27
28
# File 'lib/sandal/enc/agcm.rb', line 23

def initialize(name, aes_size, alg)
  @name = name
  @aes_size = aes_size
  @cipher_name = "aes-#{aes_size}-gcm"
  @alg = alg
end

Instance Attribute Details

#algObject (readonly)

The JWA algorithm used to encrypt the content encryption key.



17
18
19
# File 'lib/sandal/enc/agcm.rb', line 17

def alg
  @alg
end

#nameObject (readonly)

The JWA name of the encryption method.



14
15
16
# File 'lib/sandal/enc/agcm.rb', line 14

def name
  @name
end

Instance Method Details

#decrypt(token) ⇒ String

Decrypts an encrypted JSON Web Token.

Parameters:

  • token (String or Array)

    The token, or token parts, to decrypt.

Returns:

  • (String)

    The token payload.



56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/sandal/enc/agcm.rb', line 56

def decrypt(token)
  parts, decoded_parts = Sandal::Enc.token_parts(token)
  cipher = OpenSSL::Cipher.new(@cipher_name).decrypt
  begin
    cipher.key = @alg.decrypt_key(decoded_parts[1])
    cipher.iv = decoded_parts[2]
    cipher.auth_tag = decoded_parts[4]
    cipher.auth_data = parts[0]
    cipher.update(decoded_parts[3]) + cipher.final
  rescue OpenSSL::Cipher::CipherError => e
    raise Sandal::InvalidTokenError, "Cannot decrypt token: #{e.message}"
  end
end

#encrypt(header, payload) ⇒ String

Encrypts a token payload.

Parameters:

  • header (String)

    The header string.

  • payload (String)

    The payload.

Returns:

  • (String)

    An encrypted JSON Web Token.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/sandal/enc/agcm.rb', line 35

def encrypt(header, payload)
  cipher = OpenSSL::Cipher.new(@cipher_name).encrypt
  key = @alg.respond_to?(:preshared_key) ? @alg.preshared_key : cipher.random_key
  encrypted_key = @alg.encrypt_key(key)

  cipher.key = key
  cipher.iv = iv = SecureRandom.random_bytes(@@iv_size / 8)

  auth_data = Sandal::Util.jwt_base64_encode(header)
  cipher.auth_data  = auth_data

  ciphertext = cipher.update(payload) + cipher.final
  remaining_parts = [encrypted_key, iv, ciphertext, cipher.auth_tag(@@auth_tag_size / 8)]
  remaining_parts.map! { |part| Sandal::Util.jwt_base64_encode(part) }
  [auth_data, *remaining_parts].join(".")
end