Class: Arcanus::Key

Inherits:
Object
  • Object
show all
Defined in:
lib/arcanus/key.rb

Overview

Encapsulates operations for creating keys that encrypt/decrypt secrets.

Constant Summary collapse

DEFAULT_SIZE =
4096
PEM_PASSWORD_CIPHER =
OpenSSL::Cipher.new('AES-256-CBC')

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Key

Returns a new instance of Key.


32
33
34
# File 'lib/arcanus/key.rb', line 32

def initialize(key)
  @key = key
end

Class Method Details

.from_file(file_path) ⇒ Object


15
16
17
18
19
20
21
# 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) ⇒ Object


23
24
25
26
27
28
29
# 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) ⇒ Object


10
11
12
13
# 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

Instance Method Details

#decrypt(ciphertext) ⇒ Object


51
52
53
# File 'lib/arcanus/key.rb', line 51

def decrypt(ciphertext)
  @key.private_decrypt(ciphertext)
end

#encrypt(plaintext) ⇒ Object


47
48
49
# File 'lib/arcanus/key.rb', line 47

def encrypt(plaintext)
  @key.public_encrypt(plaintext)
end

#save(key_file_path:, password: nil) ⇒ Object


36
37
38
39
40
41
42
43
44
45
# 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