Class: Itamae::Secrets::Decryptor

Inherits:
Object
  • Object
show all
Defined in:
lib/itamae/secrets/decryptor.rb

Constant Summary collapse

ALGORITHM =
'aes-256-gcm'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ciphertext, auth_tag, iv, key_name, key = nil) ⇒ Decryptor

Returns a new instance of Decryptor.



23
24
25
26
27
28
29
30
# File 'lib/itamae/secrets/decryptor.rb', line 23

def initialize(ciphertext, auth_tag, iv, key_name, key = nil)
  ensure_algorithm_key_compatiblity!(key) if key
  @ciphertext = ciphertext
  @auth_tag = auth_tag
  @iv = iv
  @key_name = key_name
  @key = key
end

Instance Attribute Details

#auth_tagObject (readonly)

Returns the value of attribute auth_tag.



32
33
34
# File 'lib/itamae/secrets/decryptor.rb', line 32

def auth_tag
  @auth_tag
end

#ciphertextObject (readonly)

Returns the value of attribute ciphertext.



32
33
34
# File 'lib/itamae/secrets/decryptor.rb', line 32

def ciphertext
  @ciphertext
end

#ivObject (readonly)

Returns the value of attribute iv.



32
33
34
# File 'lib/itamae/secrets/decryptor.rb', line 32

def iv
  @iv
end

#keyObject

Returns the value of attribute key.



33
34
35
# File 'lib/itamae/secrets/decryptor.rb', line 33

def key
  @key
end

#key_nameObject (readonly)

Returns the value of attribute key_name.



32
33
34
# File 'lib/itamae/secrets/decryptor.rb', line 32

def key_name
  @key_name
end

Class Method Details

.load_json(json, key = nil) ⇒ Object

Raises:

  • (ArgumentError)


8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/itamae/secrets/decryptor.rb', line 8

def self.load_json(json, key = nil)
  data = JSON.parse(json)

  raise ArgumentError, "unknown version #{data['version'].inspect}" if data['version'] != 1
  raise ArgumentError, "unknown version #{data['algorithm'].inspect}" if data['algorithm'] != ALGORITHM

  new(
    data['ciphertext'],
    data['auth_tag'],
    data['iv'],
    data['key_name'],
    key
  )
end

Instance Method Details

#algorithmObject



52
53
54
# File 'lib/itamae/secrets/decryptor.rb', line 52

def algorithm
  ALGORITHM
end

#cipherObject



56
57
58
59
60
61
62
63
64
65
# File 'lib/itamae/secrets/decryptor.rb', line 56

def cipher
  @cipher ||= OpenSSL::Cipher.new(algorithm).tap do |c|
    raise 'key is required to proceed' unless key
    c.decrypt
    c.key = key.to_s
    c.iv = iv.unpack('m*')[0]
    c.auth_data = ''
    c.auth_tag = auth_tag.unpack('m*')[0]
  end
end

#plaintextObject



41
42
43
44
45
46
# File 'lib/itamae/secrets/decryptor.rb', line 41

def plaintext
  @plaintext ||= begin
    txt = cipher.update(ciphertext.unpack('m*')[0])
    txt << cipher.final
  end
end

#versionObject



48
49
50
# File 'lib/itamae/secrets/decryptor.rb', line 48

def version
  1
end