class Itamae::Secrets::Encryptor

Constants

ALGORITHM

Attributes

key[R]
plaintext[R]

Public Class Methods

new(plaintext, key = nil, iv = nil) click to toggle source
# 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

Public Instance Methods

algorithm() click to toggle source
# File lib/itamae/secrets/encryptor.rb, line 61
def algorithm
  ALGORITHM
end
auth_tag() click to toggle source
# 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
cipher() click to toggle source
# 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
ciphertext() click to toggle source
# 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
data()
Alias for: to_s
iv() click to toggle source
# File lib/itamae/secrets/encryptor.rb, line 45
def iv
  @iv && [@iv].pack('m*')
end
key=(other) click to toggle source
# File lib/itamae/secrets/encryptor.rb, line 17
def key=(other)
  raise "can't overwrite" if @key
  ensure_algorithm_key_compatiblity!(other)
  @key = other
end
to_s() click to toggle source
# 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
Also aliased as: data
version() click to toggle source
# File lib/itamae/secrets/encryptor.rb, line 57
def version
  1
end

Private Instance Methods

ensure_algorithm_key_compatiblity!(key) click to toggle source
# File lib/itamae/secrets/encryptor.rb, line 79
def ensure_algorithm_key_compatiblity!(key)
  unless key.algorithm_compatible?(algorithm)
    raise ArgumentError, "#{key.type} is not compatible"
  end
end