-
Notifications
You must be signed in to change notification settings - Fork 98
/
certificate.go
246 lines (201 loc) · 6.02 KB
/
certificate.go
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/*
Copyright Sparebanken Vest
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package client
import (
"bytes"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"strings"
"golang.org/x/crypto/pkcs12"
)
// CertificateKeyType contains the private key type
type CertificateKeyType string
const (
// CertificateKeyTypeRsa represents private key type RSA
CertificateKeyTypeRsa CertificateKeyType = "rsa"
// CertificateKeyTypeEcdsa represents private key type ECDSA
CertificateKeyTypeEcdsa = "ecdsa"
)
// Certificate handles data on Certificates from Azure Key Vault
type Certificate struct {
// Has the complete certificate with both public and private keys, if both exists
Certificates []*x509.Certificate
PrivateKeyRaw []byte
PrivateKeyRsa *rsa.PrivateKey
PrivateKeyEcdsa *ecdsa.PrivateKey
raw []byte
PrivateKeyType CertificateKeyType
// Indicate if Certificate has private key
HasPrivateKey bool
}
// NewCertificateFromPem creates a new Certificate from a base64 encoded pem string
func NewCertificateFromPem(pem string) (*Certificate, error) {
// privateDer, rest := pem.Decode([]byte(c.cert))
// publicDer, _ := pem.Decode(rest)
cert, err := importPem(pem, false)
if err != nil {
return nil, err
}
cert.raw = []byte(pem)
return cert, nil
}
// NewCertificateFromPfx creates a new Certificate from a PFX certificate
func NewCertificateFromPfx(pfx []byte, ensureServerFirst bool) (*Certificate, error) {
pemList, err := pkcs12.ToPEM(pfx, "")
if err != nil {
return nil, fmt.Errorf("failed to convert pfx to pem, error: %+v", err)
}
var mergedPems bytes.Buffer
for _, pemCert := range pemList {
mergedPems.WriteString(string(pem.EncodeToMemory(pemCert)))
}
cert, err := importPem(mergedPems.String(), ensureServerFirst)
if err != nil {
return nil, err
}
cert.raw = pfx
return cert, nil
}
// NewCertificateFromDer creates a new Certificate from a public cer key
func NewCertificateFromDer(der []byte) (*Certificate, error) {
var cert Certificate
pubCerts, err := x509.ParseCertificates(der)
if err != nil {
return nil, fmt.Errorf("failed to parse der certificate, error: *%+v", err)
}
cert.HasPrivateKey = false
cert.Certificates = append(cert.Certificates, pubCerts...)
cert.raw = der
return &cert, nil
}
// ExportPrivateKeyAsPem returns a pem formatted certificate
func (cert *Certificate) ExportPrivateKeyAsPem() ([]byte, error) {
if !cert.HasPrivateKey {
return nil, fmt.Errorf("certificate has no private key")
}
var derKey []byte
var keyType string
var err error
switch cert.PrivateKeyType {
case CertificateKeyTypeRsa:
derKey = x509.MarshalPKCS1PrivateKey(cert.PrivateKeyRsa)
keyType = "RSA PRIVATE KEY"
case CertificateKeyTypeEcdsa:
derKey, err = x509.MarshalECPrivateKey(cert.PrivateKeyEcdsa)
if err != nil {
return nil, err
}
keyType = "EC PRIVATE KEY"
default:
return nil, fmt.Errorf("private key type '%s' currently not supported for pem export", cert.PrivateKeyType)
}
privKeyBlock := &pem.Block{
Type: keyType,
Bytes: derKey,
}
return pem.EncodeToMemory(privKeyBlock), nil
}
// ExportPublicKeyAsPem returns a pem formatted certificate
func (cert *Certificate) ExportPublicKeyAsPem() ([]byte, error) {
if len(cert.Certificates) == 0 {
return nil, fmt.Errorf("certificate has no public key")
}
var certs strings.Builder
for _, pubCert := range cert.Certificates {
privKeyBlock := &pem.Block{
Type: "CERTIFICATE",
Bytes: pubCert.Raw,
}
certs.Write(pem.EncodeToMemory(privKeyBlock))
}
return []byte(certs.String()), nil
}
// ExportRaw returns the raw format of the original certificate
func (cert *Certificate) ExportRaw() []byte {
return cert.raw
}
func importPem(pemCert string, ensureServerFirst bool) (*Certificate, error) {
var cert Certificate
var publicDers [][]byte
var joinedPublicDers []byte
var err error
raw := []byte(pemCert)
for {
pemBlock, rest := pem.Decode(raw)
if pemBlock == nil {
break
}
if pemBlock.Type == "CERTIFICATE" {
publicDers = append(publicDers, pemBlock.Bytes)
} else {
err = parsePrivateKey(pemBlock.Bytes, &cert)
if err != nil {
return nil, err
}
}
raw = rest
}
if ensureServerFirst && len(publicDers) > 1 {
publicDers = append(
publicDers[len(publicDers)-1:],
publicDers[0:len(publicDers)-1]...,
)
}
for _, der := range publicDers {
joinedPublicDers = append(joinedPublicDers, der...)
}
cert.Certificates, err = x509.ParseCertificates(joinedPublicDers)
if err != nil {
return nil, err
}
return &cert, nil
}
func parsePrivateKey(der []byte, out *Certificate) error {
var err error
if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
out.HasPrivateKey = true
out.PrivateKeyRaw = der
out.PrivateKeyRsa = key
out.PrivateKeyType = CertificateKeyTypeRsa
return nil
}
if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
switch key := key.(type) {
case *rsa.PrivateKey:
out.HasPrivateKey = true
out.PrivateKeyRaw = der
out.PrivateKeyRsa = key
out.PrivateKeyType = CertificateKeyTypeRsa
return nil
case *ecdsa.PrivateKey:
out.HasPrivateKey = true
out.PrivateKeyRaw = der
out.PrivateKeyEcdsa = key
out.PrivateKeyType = CertificateKeyTypeEcdsa
return nil
default:
return fmt.Errorf("unknown private key type found while parsing pkcs#8 - only rsa and ecdsa supported")
}
}
if key, err := x509.ParseECPrivateKey(der); err == nil {
out.HasPrivateKey = true
out.PrivateKeyRaw = der
out.PrivateKeyEcdsa = key
out.PrivateKeyType = CertificateKeyTypeEcdsa
return nil
}
return fmt.Errorf("Failed to parse private key, error: %+v", err)
}