Class: WorkOS::Encryptors::AesGcm

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

Constant Summary collapse

SEAL_VERSION =
0x01
MIN_KEY_BYTES =

Minimum cookie_password byte length. AES-256-GCM derives a 32-byte key from the password via SHA-256; a passphrase shorter than the output it derives to provides less than the full keyspace and makes offline brute-force feasible. See README + V7_MIGRATION_GUIDE.md.

32

Instance Method Summary collapse

Instance Method Details

#seal(data, key) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'lib/workos/encryptors/aes_gcm.rb', line 23

def seal(data, key)
  validate_key!(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



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/workos/encryptors/aes_gcm.rb', line 34

def unseal(sealed, key)
  validate_key!(key)
  raw = Base64.decode64(sealed.to_s)
  begin
    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
end