We can't find the internet
Attempting to reconnect
Something went wrong!
Hang in there while we get back on track
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.
import (
"crypto/tls"
"crypto/x509"
"errors"
)
func ParseCertificate(certificateBytes []byte, privateKeyBytes []byte) (tls.Certificate, error) {
var cert tls.Certificate
var err error
cert, err = tls.X509KeyPair([]byte(certificateBytes), []byte(privateKeyBytes))
if err != nil {
return cert, err
}
if len(cert.Certificate) > 1 {
return cert, errors.New("PEM file contains multiple certificates")
}
c, err := x509.ParseCertificate(cert.Certificate[0])
if c != nil && err == nil {
cert.Leaf = c
}
return cert, nil
}
func 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.