Today, a code snippet that shows how to parse a certificate from a PEM-encoded key pair using Go. The function tls.X509KeyPair
will do the hard work for us.
1import (
2 "crypto/tls"
3 "crypto/x509"
4 "errors"
5)
6
7func ParseCertificate(certificateBytes []byte, privateKeyBytes []byte) (tls.Certificate, error) {
8
9 var cert tls.Certificate
10 var err error
11
12 cert, err = tls.X509KeyPair([]byte(certificateBytes), []byte(privateKeyBytes))
13 if err != nil {
14 return cert, err
15 }
16
17 if len(cert.Certificate) > 1 {
18 return cert, errors.New("PEM file contains multiple certificates")
19 }
20
21 c, err := x509.ParseCertificate(cert.Certificate[0])
22 if c != nil && err == nil {
23 cert.Leaf = c
24 }
25
26 return cert, nil
27
28}
1func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error)
X509KeyPair
parses a public/private key pair from a pair of PEM encoded data. On successful return,Certificate.Leaf
will be nil because the parsed form of the certificate is not retained.
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.