-
Notifications
You must be signed in to change notification settings - Fork 6
/
sec_pkcs.go
60 lines (56 loc) · 1.49 KB
/
sec_pkcs.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
package object
import (
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
p12 "software.sslmate.com/src/go-pkcs12"
)
// PKCS returns the PKCS#12 format bytes of the private key and certificate
// chain stored in this secure keystore
func (t *sec) PKCS() ([]byte, error) {
if !t.HasKey("private_key") {
return nil, fmt.Errorf("private_key does not exist")
}
privateKeyBytes, err := t.DecodeKey("private_key")
if err != nil {
return nil, err
}
block, rest := pem.Decode(privateKeyBytes)
if block == nil || block.Type != "PRIVATE KEY" {
return nil, fmt.Errorf("failed to decode PEM block containing private key")
}
privateKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
if !t.HasKey("certificate_chain") {
return nil, fmt.Errorf("certificate_chain does not exist")
}
certificateChainBytes, err := t.DecodeKey("certificate_chain")
if err != nil {
return nil, err
}
l := make([]*x509.Certificate, 0)
for {
block, certificateChainBytes = pem.Decode(certificateChainBytes)
if block == nil {
break
}
if block.Type != "CERTIFICATE" {
return nil, fmt.Errorf("failed to decode PEM block containing certificate. actual type %s", block.Type)
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
l = append(l, cert)
if rest == nil {
break
}
}
if len(l) < 1 {
return nil, fmt.Errorf("certificate_chain has no valid certificate")
}
return p12.Encode(rand.Reader, privateKey, l[0], l[1:], "foo")
}