Sha256: 1099f915c445271f7f5790b62d488a1923a441767cdef038a890ec38ccbed90d

Contents?: true

Size: 1.57 KB

Versions: 3

Compression:

Stored size: 1.57 KB

Contents

# frozen_string_literal: true

module Xml
  module Kit
    class SelfSignedCertificate
      SUBJECT = '/C=CA/ST=AB/L=Calgary/O=XmlKit/OU=XmlKit/CN=XmlKit'

      def create(algorithm: 'AES-256-CBC',
                 passphrase: nil,
                 key_pair: OpenSSL::PKey::RSA.new(2048))
        certificate = certificate_for(key_pair.public_key)
        certificate.sign(key_pair, OpenSSL::Digest::SHA256.new)
        [certificate.to_pem, export(key_pair, algorithm, passphrase)]
      end

      private

      def export(key_pair, algorithm, passphrase)
        if passphrase.present?
          cipher = OpenSSL::Cipher.new(algorithm)
          key_pair.export(cipher, passphrase)
        else
          key_pair.export
        end
      end

      def certificate_for(public_key)
        certificate = OpenSSL::X509::Certificate.new
        certificate.subject =
          certificate.issuer = OpenSSL::X509::Name.parse(SUBJECT)
        certificate.not_before = Time.now
        certificate.not_after = certificate.not_before + 30 * 24 * 60 * 60 # 30 days
        certificate.public_key = public_key
        certificate.serial = 0x0
        certificate.version = 2
        apply_ski_extension_to(certificate)
        certificate
      end

      def apply_ski_extension_to(certificate)
        extensions = OpenSSL::X509::ExtensionFactory.new
        extensions.subject_certificate = certificate
        extensions.issuer_certificate = certificate
        certificate.add_extension(
          extensions.create_extension('subjectKeyIdentifier', 'hash', false)
        )
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
xml-kit-0.6.0 lib/xml/kit/self_signed_certificate.rb
xml-kit-0.5.0 lib/xml/kit/self_signed_certificate.rb
xml-kit-0.4.0 lib/xml/kit/self_signed_certificate.rb