This repository has been archived by the owner on Sep 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexport.go
96 lines (83 loc) · 2.45 KB
/
export.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
package certbox
import (
"fmt"
"github.com/tls-inspector/certbox-go/tls"
)
// Export formats
const (
FormatPEM = "PEM"
FormatP12 = "PKCS12"
FormatDER = "DER"
)
// ExportCertificatesParameters describes the parameters for exporting a certificate
type ExportCertificatesParameters struct {
Certificates []tls.Certificate
Format string
Password string
}
// ExportedCertificate describes the response from exporting a certificate
type ExportedCertificate struct {
Name string
Data []byte
}
// ExportCertificates will generate appropriate files for the given certificates
func ExportCertificates(parameters ExportCertificatesParameters) ([]ExportedCertificate, error) {
var root *tls.Certificate
for _, certificate := range parameters.Certificates {
if !certificate.X509().IsCA {
continue
}
root = &certificate
}
exportedCertificates := []ExportedCertificate{}
for _, certificate := range parameters.Certificates {
switch parameters.Format {
case FormatPEM:
certData, keyData, err := tls.ExportPEM(&certificate)
if err != nil {
return nil, err
}
exportedCertificates = append(exportedCertificates, []ExportedCertificate{
{
Name: filenameSafeString(certificate.Subject.CommonName) + "_" + certificate.Serial[0:8] + ".crt",
Data: certData,
},
{
Name: filenameSafeString(certificate.Subject.CommonName) + "_" + certificate.Serial[0:8] + ".key",
Data: keyData,
},
}...)
case FormatDER:
certData, keyData, err := tls.ExportDER(&certificate)
if err != nil {
return nil, err
}
exportedCertificates = append(exportedCertificates, []ExportedCertificate{
{
Name: filenameSafeString(certificate.Subject.CommonName) + "_" + certificate.Serial[0:8] + ".crt",
Data: certData,
},
{
Name: filenameSafeString(certificate.Subject.CommonName) + "_" + certificate.Serial[0:8] + ".key",
Data: keyData,
},
}...)
case FormatP12:
var ca *tls.Certificate
if !certificate.CertificateAuthority {
ca = root
}
p12Data, err := tls.ExportPKCS12(&certificate, ca, parameters.Password)
if err != nil {
return nil, err
}
exportedCertificates = append(exportedCertificates, ExportedCertificate{
Name: filenameSafeString(certificate.Subject.CommonName) + "_" + certificate.Serial[0:8] + ".p12",
Data: p12Data,
})
default:
return nil, fmt.Errorf("unknown export format %s", parameters.Format)
}
}
return exportedCertificates, nil
}