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.

Related Posts

  • Embedding file with Go 1.16
  • Truncating a Unix timestamp to the hour using Go
  • Gotcha with defer in Go
  • Looking up a CNAME in Go
  • Pretty-print JSON with Go