Class: Itamae::Secrets::Encryptor

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

Constant Summary collapse

ALGORITHM =
'aes-256-gcm'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(plaintext, key = nil, iv = nil) ⇒ Encryptor

Returns a new instance of Encryptor.



8
9
10
11
12
13
# File 'lib/itamae/secrets/encryptor.rb', line 8

def initialize(plaintext, key = nil, iv = nil)
  ensure_algorithm_key_compatiblity!(key) if key
  @key = key
  @iv = iv
  @plaintext = plaintext
end

Instance Attribute Details

#keyObject

Returns the value of attribute key.



15
16
17
# File 'lib/itamae/secrets/encryptor.rb', line 15

def key
  @key
end

#plaintextObject (readonly)

Returns the value of attribute plaintext.



15
16
17
# File 'lib/itamae/secrets/encryptor.rb', line 15

def plaintext
  @plaintext
end

Instance Method Details

#algorithmObject



61
62
63
# File 'lib/itamae/secrets/encryptor.rb', line 61

def algorithm
  ALGORITHM
end

#auth_tagObject



49
50
51
52
53
54
55
# File 'lib/itamae/secrets/encryptor.rb', line 49

def auth_tag
  if @auth_tag
    [@auth_tag].pack('m*')
  else
    raise '[BUG] auth_tag not exists'
  end
end

#cipherObject



65
66
67
68
69
70
71
72
73
74
75
# File 'lib/itamae/secrets/encryptor.rb', line 65

def cipher
  @cipher ||= OpenSSL::Cipher.new(algorithm).tap do |c|
    raise 'key is required to proceed' unless key
    c.encrypt
    c.key = key.to_s
    # XXX: avoid generate IV here, but consider if extract to a method like #iv, it have to know Cipher#iv_len...
    @iv ||= c.random_iv
    c.iv = @iv
    c.auth_data = ''
  end
end

#ciphertextObject



36
37
38
39
40
41
42
43
# File 'lib/itamae/secrets/encryptor.rb', line 36

def ciphertext
  @ciphertext ||= begin
    data = cipher.update(plaintext)
    data << cipher.final
    @auth_tag = cipher.auth_tag
    [data].pack('m*')
  end
end

#ivObject



45
46
47
# File 'lib/itamae/secrets/encryptor.rb', line 45

def iv
  @iv && [@iv].pack('m*')
end

#to_sObject Also known as: data



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

def to_s
  {
    version: version,
    algorithm: algorithm,
    key_name: key.name,
    ciphertext: ciphertext,
    iv: iv,
    auth_tag: auth_tag,
  }.to_json
end

#versionObject



57
58
59
# File 'lib/itamae/secrets/encryptor.rb', line 57

def version
  1
end