Class: BBK::Utils::Crypt

Inherits:
Object
  • Object
show all
Defined in:
lib/bbk/utils/crypt.rb

Class Method Summary collapse

Class Method Details

.full_check(key_path, cert_path, *cacert_chain) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/bbk/utils/crypt.rb', line 9

def self.full_check(key_path, cert_path, *cacert_chain)
  errors = []
  errors << 'Invalid key and cert pair' unless valid_key_cert?(key_path, cert_path)
  errors << 'Invalid cert and cacert pair' unless valid_cert_sign?(cert_path,
                                                                   *cacert_chain.compact)
  if errors.empty?
    nil
  else
    errors
  end
end

.valid_cert_sign?(cert_path, *ca_certs_paths) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
33
34
35
36
37
# File 'lib/bbk/utils/crypt.rb', line 30

def self.valid_cert_sign?(cert_path, *ca_certs_paths)
  raise "Cert file #{cert_path} not exists" unless File.exist? cert_path
  raise "Not all files in ca chain #{ca_certs_paths} exists" unless ca_certs_paths.all? {|pth| File.exist? pth }

  store = ca_certs_paths.reduce(OpenSSL::X509::Store.new) {|st, c| st.add_file(c) }
  cert = OpenSSL::X509::Certificate.new File.read(cert_path)
  store.verify(cert)
end

.valid_key_cert?(key_path, cert_path) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
24
25
26
27
28
# File 'lib/bbk/utils/crypt.rb', line 21

def self.valid_key_cert?(key_path, cert_path)
  raise "Key file #{key_path} not exists" unless File.exist? key_path
  raise "Cert file #{cert_path} not exists" unless File.exist? cert_path

  key = OpenSSL::PKey::RSA.new(File.read(key_path))
  cert = OpenSSL::X509::Certificate.new(File.read(cert_path))
  cert.check_private_key(key)
end