class EncryptedKeystore

Attributes

file[RW]
iv[RW]
key[RW]
out[RW]

Public Class Methods

decrypt(file: nil, out: nil, key: nil, iv: nil) click to toggle source
# File lib/encrypted_keystore.rb, line 16
def self.decrypt(file: nil, out: nil, key: nil, iv: nil)
  enc = new(file: file, out: out, key: key, iv: iv)
  enc.decrypt
end
encrypt(file: nil, out: nil) click to toggle source
# File lib/encrypted_keystore.rb, line 9
def self.encrypt(file: nil, out: nil)
  enc = new(file: file, out: out)
  enc.encrypt

  { key: enc.key, iv: enc.iv }
end
new(file: nil, out: nil, key: nil, iv: nil) click to toggle source
# File lib/encrypted_keystore.rb, line 21
def initialize(file: nil, out: nil, key: nil, iv: nil)
  @file = file
  @out = out
  @key = key
  @iv = iv
end

Public Instance Methods

decrypt() click to toggle source
# File lib/encrypted_keystore.rb, line 28
def decrypt
  validate

  write(dec_cipher)
  FileUtils.chmod(0o0600, @out)
  @out
end
encrypt() click to toggle source
# File lib/encrypted_keystore.rb, line 36
def encrypt
  validate(enc: true)

  write(enc_cipher)
end

Private Instance Methods

dec_cipher() click to toggle source
# File lib/encrypted_keystore.rb, line 44
def dec_cipher
  cipher = OpenSSL::Cipher.new('aes-256-cbc')
  cipher.decrypt
  cipher.key = Base64.decode64(@key)
  cipher.iv = Base64.decode64(@iv)
  cipher
end
enc_cipher() click to toggle source
# File lib/encrypted_keystore.rb, line 52
def enc_cipher
  cipher = OpenSSL::Cipher.new('aes-256-cbc')
  cipher.encrypt
  @key = Base64.encode64(cipher.random_key)
  @iv = Base64.encode64(cipher.random_iv)
  cipher
end
validate(enc: false) click to toggle source
# File lib/encrypted_keystore.rb, line 74
def validate(enc: false)
  return true if !@file.nil? && !@out.nil? && (!enc || (!@key.nil? && !@iv.nil?))

  raise ArgumentError, 'Required arguments have not been provided.'
end
write(cipher) click to toggle source
# File lib/encrypted_keystore.rb, line 60
def write(cipher)
  validate

  buffer = +''
  File.open(@out, 'wb') do |outfile|
    File.open(@file, 'rb') do |infile|
      outfile << cipher.update(buffer) while infile.read(4096, buffer)
      outfile << cipher.final
    end
  end

  @out
end