Class: MyPKI::PEM

Inherits:
Object
  • Object
show all
Includes:
Configuration::Loader, Prompter
Defined in:
lib/mypki/loaders/pem.rb

Instance Attribute Summary

Attributes included from Configuration::Loader

#options

Instance Method Summary collapse

Methods included from Configuration::Loader

included, #initialize

Methods included from Prompter

#file_prompt, #pass_prompt, #prompter

Instance Method Details

#configure(config, path) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/mypki/loaders/pem.rb', line 8

def configure config, path
  if %w[pem id_rsa key crt cert].any? {|ext| path.end_with? ext}
    contents = File.read path
    config['pem'] = {}
    has_cert = false
    
    if contents['PRIVATE KEY']
      config['pem']['path'] = path
    end

    if contents['BEGIN CERTIFICATE']
      has_cert = true
    end

    if config['pem']['path']
      unless has_cert
        config['pem']['cert'] = file_prompt('Path to your certificate: ')
      end
    elsif has_cert
      config['pem']['cert'] = path
      config['pem']['path'] = file_prompt('Path to your private key: ')
    end
  end
end

#load(config) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/mypki/loaders/pem.rb', line 33

def load config 
  if config['pem']
    pem = File.read config['pem']['path']
    cert = (config['pem']['cert'])? File.read(config['pem']['cert']) : pem
    
    begin 
      Instance.cert = OpenSSL::X509::Certificate.new cert
    rescue OpenSSL::X509::CertificateError
      config['pem'] = {}
      Instance.key = Instance.cert = nil
      fail "No certificate found! Regenerate with --nocerts or provide a .key and .crt file separately."
    end
    
    begin 
      retriable do 
        if pem['ENCRYPTED']
          password = pass_prompt('PEM Passphrase:')
          Instance.key = OpenSSL::PKey::RSA.new pem, password
        else
          Instance.key = OpenSSL::PKey::RSA.new pem
        end
      end
    rescue OpenSSL::PKey::RSAError
      fail "Error: bad password"
    end
  end
end