certificate.rb 1.19 KB
require "openssl"
require 'digest/md5'

class Certificate < ActiveRecord::Base
  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 + 1.year
    cert.not_after = Time.now + 1.day
    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
  end

  def update
    self.active = false
    self.save
    cert = Certificate.create(self)
    cert.save
    cert
  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
end
# vim: set et ts=2 sw=2: