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) ⇒ Box

Returns a new instance of Box.



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

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

Instance Attribute Details

#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



18
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
# File 'lib/kms_encrypted/box.rb', line 18

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)

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

#encrypt(plaintext, context: nil) ⇒ Object



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

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).encrypt(plaintext, context: context)
  "v#{version}:#{encode64(ciphertext)}"
end