class Arcanus::Key

Encapsulates operations for creating keys that encrypt/decrypt secrets.

Constants

DEFAULT_SIZE
PEM_PASSWORD_CIPHER

Public Class Methods

from_file(file_path) click to toggle source
# File lib/arcanus/key.rb, line 15
def from_file(file_path)
  key = OpenSSL::PKey::RSA.new(File.read(file_path))
  new(key)
rescue OpenSSL::PKey::RSAError
  raise Errors::DecryptionError,
        "Invalid PEM file #{file_path}"
end
from_protected_file(file_path, password) click to toggle source
# File lib/arcanus/key.rb, line 23
def from_protected_file(file_path, password)
  key = OpenSSL::PKey::RSA.new(File.read(file_path), password)
  new(key)
rescue OpenSSL::PKey::RSAError
  raise Errors::DecryptionError,
        'Either the password is invalid or the key file is corrupted'
end
generate(key_size_bits: DEFAULT_SIZE) click to toggle source
# File lib/arcanus/key.rb, line 10
def generate(key_size_bits: DEFAULT_SIZE)
  key = OpenSSL::PKey::RSA.new(key_size_bits)
  new(key)
end
new(key) click to toggle source
# File lib/arcanus/key.rb, line 32
def initialize(key)
  @key = key
end

Public Instance Methods

decrypt(ciphertext) click to toggle source
# File lib/arcanus/key.rb, line 51
def decrypt(ciphertext)
  @key.private_decrypt(ciphertext)
end
encrypt(plaintext) click to toggle source
# File lib/arcanus/key.rb, line 47
def encrypt(plaintext)
  @key.public_encrypt(plaintext)
end
save(key_file_path:, password: nil) click to toggle source
# File lib/arcanus/key.rb, line 36
def save(key_file_path:, password: nil)
  pem =
    if password
      @key.to_pem(PEM_PASSWORD_CIPHER, password)
    else
      @key.to_pem
    end

  File.open(key_file_path, 'w') { |f| f.write(pem) }
end