certificate.rb
1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
require "openssl"
require 'digest/md5'
class Certificate < ActiveRecord::Base
private_class_method :new
def self.get
@@cert ||= find_by active: true
@@cert ||= create
@@cert = @@cert.update if @@cert.expires_soon?
@@cert
end
def self.create(old=nil)
key = if old then old.key else OpenSSL::PKey::RSA.new 4096 end
cert = OpenSSL::X509::Certificate.new
cert.version = if old then old.cert.version else 2 end
cert.serial = if old then old.cert.serial+1 else 0 end
cert.not_before = Time.now
#cert.not_after = Time.now + 3.months
cert.not_after = Time.now + 1.day + 5.minutes
cert.public_key = key.public_key
cert.subject =
OpenSSL::X509::Name.parse(
'CN=lex-deeit/' + Rails.configuration.x.certificate['x509_base'])
cert.sign key, OpenSSL::Digest::SHA256.new
certificate = new(key: key.to_pem, cert: cert.to_pem, active: true)
certificate.save
certificate
end
def update
self.active = false
self.save
Certificate.create(self)
end
def is_expired?
# The cert is already expired
self.cert.not_after < Time.now
end
def expires_soon?
# The cert will expire within the next day or is alreay expired
(self.cert.not_after - 1.day) < Time.now
end
def key
OpenSSL::PKey::RSA.new read_attribute(
:key) if read_attribute(:key)
end
def cert
OpenSSL::X509::Certificate.new read_attribute(
:cert) if read_attribute(:cert)
end
def key_fpr
Digest::SHA256.hexdigest(key.to_der).upcase
end
def cert_fpr
Digest::SHA256.hexdigest(cert.to_der).upcase
end
def to_s
cert.to_pem.split("\n")[1...-1].join
end
def to_str
to_s
end
end
# vim: set et ts=2 sw=2: