Class: KmsEncrypted::Box

Inherits:
Object
  • Object
show all
Defined in:
lib/kms_encrypted/box.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key_id: nil, version: nil, previous_versions: nil, client: nil) ⇒ Box



5
6
7
8
9
10
# File 'lib/kms_encrypted/box.rb', line 5

def initialize(key_id: nil, version: nil, previous_versions: nil, client: nil)
  @key_id = key_id || KmsEncrypted.key_id
  @version = version || 1
  @previous_versions = previous_versions || {}
  @client = client
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



3
4
5
# File 'lib/kms_encrypted/box.rb', line 3

def client
  @client
end

#key_idObject (readonly)

Returns the value of attribute key_id.



3
4
5
# File 'lib/kms_encrypted/box.rb', line 3

def key_id
  @key_id
end

#previous_versionsObject (readonly)

Returns the value of attribute previous_versions.



3
4
5
# File 'lib/kms_encrypted/box.rb', line 3

def previous_versions
  @previous_versions
end

#versionObject (readonly)

Returns the value of attribute version.



3
4
5
# File 'lib/kms_encrypted/box.rb', line 3

def version
  @version
end

Instance Method Details

#decrypt(ciphertext, context: nil) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/kms_encrypted/box.rb', line 19

def decrypt(ciphertext, context: nil)
  m = /\Av(\d+):/.match(ciphertext)
  if m
    version = m[1].to_i
    ciphertext = ciphertext.sub("v#{version}:", "")
  else
    version = 1
    legacy_context = true

    # legacy
    if ciphertext.start_with?("$gc$")
      _, _, short_key_id, ciphertext = ciphertext.split("$", 4)

      # restore key, except for cryptoKeyVersion
      stored_key_id = decode64(short_key_id).split("/")[0..3]
      stored_key_id.insert(0, "projects")
      stored_key_id.insert(2, "locations")
      stored_key_id.insert(4, "keyRings")
      stored_key_id.insert(6, "cryptoKeys")
      key_id = stored_key_id.join("/")
    elsif ciphertext.start_with?("vault:")
      ciphertext = Base64.encode64(ciphertext)
    end
  end

  key_id ||= version_key_id(version)
  ciphertext = decode64(ciphertext)
  context = version_context(context, version)
  client = version_client(version)

  KmsEncrypted::Client.new(
    key_id: key_id,
    data_key: true,
    legacy_context: legacy_context,
    client: client
  ).decrypt(ciphertext, context: context)
end

#encrypt(plaintext, context: nil) ⇒ Object



12
13
14
15
16
17
# File 'lib/kms_encrypted/box.rb', line 12

def encrypt(plaintext, context: nil)
  context = version_context(context, version)
  key_id = version_key_id(version)
  ciphertext = KmsEncrypted::Client.new(key_id: key_id, data_key: true, client: client).encrypt(plaintext, context: context)
  "v#{version}:#{encode64(ciphertext)}"
end