aboutsummaryrefslogtreecommitdiff
path: root/vendor/certificate_authority/lib/certificate_authority/key_material.rb
blob: 1fd4dd920de8626b05bd2325219aec259e1fbb6b (plain)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
module CertificateAuthority
  module KeyMaterial
    def public_key
      raise "Required implementation"
    end

    def private_key
      raise "Required implementation"
    end

    def is_in_hardware?
      raise "Required implementation"
    end

    def is_in_memory?
      raise "Required implementation"
    end

    def self.from_x509_key_pair(pair,password=nil)
      if password.nil?
        key = OpenSSL::PKey::RSA.new(pair)
      else
        key = OpenSSL::PKey::RSA.new(pair,password)
      end
      mem_key = MemoryKeyMaterial.new
      mem_key.public_key = key.public_key
      mem_key.private_key = key
      mem_key
    end

    def self.from_x509_public_key(public_key_pem)
      key = OpenSSL::PKey::RSA.new(public_key_pem)
      signing_request_key = SigningRequestKeyMaterial.new
      signing_request_key.public_key = key.public_key
      signing_request_key
    end
  end

  class MemoryKeyMaterial
    include KeyMaterial
    include ActiveModel::Validations

    attr_accessor :keypair
    attr_accessor :private_key
    attr_accessor :public_key

    def initialize
    end

    validates_each :private_key do |record, attr, value|
        record.errors.add :private_key, "cannot be blank" if record.private_key.nil?
    end
    validates_each :public_key do |record, attr, value|
      record.errors.add :public_key, "cannot be blank" if record.public_key.nil?
    end

    def is_in_hardware?
      false
    end

    def is_in_memory?
      true
    end

    def generate_key(modulus_bits=2048)
      self.keypair = OpenSSL::PKey::RSA.new(modulus_bits)
      self.private_key = keypair
      self.public_key = keypair.public_key
      self.keypair
    end

    def private_key
      @private_key
    end

    def public_key
      @public_key
    end
  end

  class SigningRequestKeyMaterial
    include KeyMaterial
    include ActiveModel::Validations

    validates_each :public_key do |record, attr, value|
      record.errors.add :public_key, "cannot be blank" if record.public_key.nil?
    end

    attr_accessor :public_key

    def initialize(request=nil)
      if request.is_a? OpenSSL::X509::Request
        raise "Invalid certificate signing request" unless request.verify request.public_key
        self.public_key = request.public_key
      end
    end

    def is_in_hardware?
      false
    end

    def is_in_memory?
      true
    end

    def private_key
      nil
    end

    def public_key
      @public_key
    end
  end
end