main
 1# frozen_string_literal: true
 2
 3module Xml
 4  module Kit
 5    class KeyPair # :nodoc:
 6      attr_reader :certificate
 7      attr_reader :private_key
 8      attr_reader :public_key
 9
10      def initialize(certificate, private_key, passphrase, use)
11        @certificate = ::Xml::Kit::Certificate.new(certificate, use: use)
12        @private_key =
13          if passphrase.present?
14            OpenSSL::PKey::RSA.new(private_key, passphrase)
15          else
16            OpenSSL::PKey::RSA.new(private_key)
17          end
18        @public_key = @private_key.public_key
19      end
20
21      # Returns true if the key pair is the designated use.
22      #
23      # @param use [Symbol] Can be either `:signing` or `:encryption`.
24      def for?(use)
25        certificate.for?(use)
26      end
27
28      # Returns a generated self signed certificate with private key.
29      #
30      # @param use [Symbol] Can be either `:signing` or `:encryption`.
31      # @param passphrase [String] the passphrase to use to encrypt the private key.
32      # @param algorithm [String] the symmetric algorithm to use for encrypting the private key.
33      def self.generate(use:,
34                        passphrase: SecureRandom.uuid,
35                        algorithm: Crypto::SymmetricCipher::DEFAULT_ALGORITHM)
36        algorithm = Crypto::SymmetricCipher::ALGORITHMS[algorithm]
37        certificate, private_key = SelfSignedCertificate.new.create(
38          algorithm: algorithm,
39          passphrase: passphrase
40        )
41        new(certificate, private_key, passphrase, use)
42      end
43    end
44  end
45end