Repository navigation
Expand file tree
/
Copy pathencode_pem.go
More file actions
49 lines (46 loc) · 1.44 KB
/
Copy pathencode_pem.go
File metadata and controls
49 lines (46 loc) · 1.44 KB
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
package certkit
import (
"bytes"
"encoding/pem"
"github.com/emmansun/gmsm/pkcs8"
"github.com/emmansun/gmsm/smx509"
"github.com/go-sdk/core/errx"
)
func (s *Store) encodePEM(options EncodeOptions, report *ConversionReport) ([]byte, error) {
var output bytes.Buffer
for _, cert := range s.Certificates {
if options.ExcludeRootCertificates && certificateRole(cert.Certificate) == CertificateRoleRoot {
report.DiscardedCertificates++
continue
}
if err := pem.Encode(&output, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Certificate.Raw}); err != nil {
return nil, errx.Wrap(err, "encode pem certificate")
}
report.CertificatesWritten++
}
for _, key := range s.PrivateKeys {
der, err := smx509.MarshalPKCS8PrivateKey(key.Signer)
if err != nil {
return nil, errx.Wrap(err, "marshal pem private key")
}
block := &pem.Block{Type: "PRIVATE KEY", Bytes: der}
if options.EncryptPEMPrivateKey {
if len(options.Password) == 0 {
return nil, ErrPassword
}
der, err = pkcs8.MarshalPrivateKey(key.Signer, options.Password, nil)
if err != nil {
return nil, errx.Wrap(err, "encrypt pem private key")
}
block = &pem.Block{Type: "ENCRYPTED PRIVATE KEY", Bytes: der}
}
if err := pem.Encode(&output, block); err != nil {
return nil, errx.Wrap(err, "encode pem private key")
}
report.PrivateKeysWritten++
}
if output.Len() == 0 {
return nil, errx.Wrap(ErrInvalidData, "store is empty")
}
return output.Bytes(), nil
}