Class: WorkOS::Encryptors::AesGcm

Inherits:
Object
  • Object
show all
Defined in:
lib/workos/encryptors/aes_gcm.rb

Constant Summary collapse

SEAL_VERSION =
0x01

Instance Method Summary collapse

Instance Method Details

#seal(data, key) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/workos/encryptors/aes_gcm.rb', line 18

def seal(data, key)
  json = data.is_a?(String) ? data : JSON.generate(data)
  cipher = OpenSSL::Cipher.new("aes-256-gcm").encrypt
  cipher.key = derive_key(key)
  iv = SecureRandom.random_bytes(12)
  cipher.iv = iv
  ciphertext = cipher.update(json) + cipher.final
  Base64.strict_encode64(SEAL_VERSION.chr + iv + cipher.auth_tag + ciphertext)
end

#unseal(sealed, key) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/workos/encryptors/aes_gcm.rb', line 28

def unseal(sealed, key)
  raw = Base64.decode64(sealed.to_s)
  decode_v7(raw, key)
rescue ArgumentError, OpenSSL::Cipher::CipherError => original_error
  begin
    decode_old(raw, key)
  rescue ArgumentError, OpenSSL::Cipher::CipherError
    raise original_error
  end
end