Skip to content

Instantly share code, notes, and snippets.

@ibejohn818
Last active August 11, 2022 20:47
Show Gist options
  • Save ibejohn818/ccbd550456574a846e4ae648ebedc14b to your computer and use it in GitHub Desktop.
Save ibejohn818/ccbd550456574a846e4ae648ebedc14b to your computer and use it in GitHub Desktop.
Load pem cert/key file into tls.Certificate
import (
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
)
/*
Load a pem file with both cert and key inside
IE:
-----BEGIN CERTIFICATE-----
{CERT CONTENTS}
-----END CERTIFICATE-----
-----BEGIN RSA PRIVATE KEY-----
{KEY CONTENTS}
-----END RSA PRIVATE KEY-----
*/
func LoadCert(path string) (*tls.Certificate, error) {
raw, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
var cert tls.Certificate
for {
block, rest := pem.Decode(raw)
if block == nil {
break
}
if block.Type == "CERTIFICATE" {
cert.Certificate = append(cert.Certificate, block.Bytes)
} else {
cert.PrivateKey, err = parsePrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("private key error \"%s\": %s", path, err)
}
}
raw = rest
}
if len(cert.Certificate) == 0 {
return nil, fmt.Errorf("cert not found\"%s\"", path)
} else if cert.PrivateKey == nil {
return nil, fmt.Errorf("key not found in \"%s\"", path)
}
return &cert, nil
}
func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
return key, nil
}
if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
switch key := key.(type) {
case *rsa.PrivateKey, *ecdsa.PrivateKey:
return key, nil
default:
return nil, fmt.Errorf("unknown key type in PKCS#8 wrapping")
}
}
if key, err := x509.ParseECPrivateKey(der); err == nil {
return key, nil
}
return nil, fmt.Errorf("error parsing key")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment