-
Notifications
You must be signed in to change notification settings - Fork 0
/
certificate.go
74 lines (66 loc) · 1.8 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
package identity
import (
"crypto/rsa"
"crypto/x509"
p "encoding/pem"
"errors"
)
var (
// ErrNoCertificates is returned when no certificates are found in the PEM.
ErrNoCertificates = errors.New("no certificates found")
// ErrNoPrivateKey is returned when no private key is found in the PEM.
ErrNoPrivateKey = errors.New("no private key found")
// ErrMultiplePrivateKeys is returned when multiple private keys are found in the PEM.
ErrMultiplePrivateKeys = errors.New("multiple private keys found")
// ErrKeyNotRSA is returned when the private key is not an RSA key.
ErrKeyNotRSA = errors.New("private key is not an RSA key")
)
// CertificatesAndKeyFromPEM extracts the x509 certificates and private key from the given PEM.
func CertificatesAndKeyFromPEM(pem []byte) ([]*x509.Certificate, *rsa.PrivateKey, error) {
var certs []*x509.Certificate
var privateKey *rsa.PrivateKey
for {
block, rest := p.Decode(pem)
if block == nil {
break
}
switch block.Type {
case "CERTIFICATE":
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, nil, err
}
certs = append(certs, cert)
case "RSA PRIVATE KEY":
if privateKey != nil {
return nil, nil, ErrMultiplePrivateKeys
}
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, nil, err
}
privateKey = key
case "PRIVATE KEY":
if privateKey != nil {
return nil, nil, ErrMultiplePrivateKeys
}
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, nil, err
}
k, ok := key.(*rsa.PrivateKey)
if !ok {
return nil, nil, ErrKeyNotRSA
}
privateKey = k
}
pem = rest
}
if certs == nil {
return nil, nil, ErrNoCertificates
}
if privateKey == nil {
return nil, nil, ErrNoPrivateKey
}
return certs, privateKey, nil
}