...
1
16
17 package cert
18
19 import (
20 "bytes"
21 "crypto/x509"
22 "encoding/pem"
23 "errors"
24 )
25
26 const (
27
28 CertificateBlockType = "CERTIFICATE"
29
30 CertificateRequestBlockType = "CERTIFICATE REQUEST"
31 )
32
33
34
35 func ParseCertsPEM(pemCerts []byte) ([]*x509.Certificate, error) {
36 ok := false
37 certs := []*x509.Certificate{}
38 for len(pemCerts) > 0 {
39 var block *pem.Block
40 block, pemCerts = pem.Decode(pemCerts)
41 if block == nil {
42 break
43 }
44
45 if block.Type != CertificateBlockType || len(block.Headers) != 0 {
46 continue
47 }
48
49 cert, err := x509.ParseCertificate(block.Bytes)
50 if err != nil {
51 return certs, err
52 }
53
54 certs = append(certs, cert)
55 ok = true
56 }
57
58 if !ok {
59 return certs, errors.New("data does not contain any valid RSA or ECDSA certificates")
60 }
61 return certs, nil
62 }
63
64
65 func EncodeCertificates(certs ...*x509.Certificate) ([]byte, error) {
66 b := bytes.Buffer{}
67 for _, cert := range certs {
68 if err := pem.Encode(&b, &pem.Block{Type: CertificateBlockType, Bytes: cert.Raw}); err != nil {
69 return []byte{}, err
70 }
71 }
72 return b.Bytes(), nil
73 }
74
View as plain text