class Sandal::Enc::AGCM

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

Attributes

alg[R]

The JWA algorithm used to encrypt the content encryption key.

name[R]

The JWA name of the encryption method.

Public Class Methods

new(name, aes_size, alg) click to toggle source

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

@param aes_size [Integer] The size of the AES algorithm, in bits. @param alg [#name, encrypt_key, decrypt_key] The algorithm to use to encrypt and/or decrypt the AES key.

# 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

Public Instance Methods

decrypt(token) click to toggle source

Decrypts an encrypted JSON Web Token.

@param token [String or Array] The token, or token parts, to decrypt. @return [String] The token payload.

# 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) click to toggle source

Encrypts a token payload.

@param header [String] The header string. @param payload [String] The payload. @return [String] An encrypted JSON Web Token.

# 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