certificate.rb 1.69 KB
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: