Class: Nanite::Certificate

Inherits:
Object show all
Defined in:
lib/nanite/security/certificate.rb

Overview

X.509 Certificate management

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, issuer, subject, valid_for = 3600*24*365*10) ⇒ Certificate

Generate a signed X.509 certificate

Arguments:

- key: RsaKeyPair, key pair used to sign certificate
- issuer: DistinguishedName, certificate issuer
- subject: DistinguishedName, certificate subject
- valid_for: Time in seconds before certificate expires (10 years by default)


16
17
18
19
20
21
22
23
24
25
26
# File 'lib/nanite/security/certificate.rb', line 16

def initialize(key, issuer, subject, valid_for = 3600*24*365*10)
  @raw_cert = OpenSSL::X509::Certificate.new
  @raw_cert.version = 2
  @raw_cert.serial = 1
  @raw_cert.subject = subject.to_x509
  @raw_cert.issuer = issuer.to_x509
  @raw_cert.public_key = key.to_public.raw_key
  @raw_cert.not_before = Time.now
  @raw_cert.not_after = Time.now + valid_for
  @raw_cert.sign(key.raw_key, OpenSSL::Digest::SHA1.new)
end

Instance Attribute Details

#raw_certObject

Underlying OpenSSL cert



7
8
9
# File 'lib/nanite/security/certificate.rb', line 7

def raw_cert
  @raw_cert
end

Class Method Details

.from_data(data) ⇒ Object

Initialize with raw certificate



34
35
36
37
38
39
# File 'lib/nanite/security/certificate.rb', line 34

def self.from_data(data)
  cert = OpenSSL::X509::Certificate.new(data)
  res = Certificate.allocate
  res.instance_variable_set(:@raw_cert, cert)
  res
end

.load(file) ⇒ Object

Load certificate from file



29
30
31
# File 'lib/nanite/security/certificate.rb', line 29

def self.load(file)
  from_data(File.new(file))
end

Instance Method Details

#dataObject Also known as: to_s

Certificate data in PEM format



49
50
51
# File 'lib/nanite/security/certificate.rb', line 49

def data
  @raw_cert.to_pem
end

#save(file) ⇒ Object

Save certificate to file in PEM format



42
43
44
45
46
# File 'lib/nanite/security/certificate.rb', line 42

def save(file)
  File.open(file, "w") do |f|
    f.write(@raw_cert.to_pem)
  end
end