I have a certificate (PEM), and I'd like to check if the certificate is valid and signed by CA. I already have the CA certificate (PEM). What is a simple, but secure way to check the certificate in Go, using the standard crypto/x509
package?
You need to use Certificate.Verify()
. There is an example for exactly what you want to do in the docs:
https://golang.org/pkg/crypto/x509/#example_Certificate_Verify
func verifyCert(rootPEM, certPEM string, name string) error {
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM([]byte(rootPEM))
if !ok {
return fmt.Errorf("failed to parse root certificate")
}
block, _ := pem.Decode([]byte(certPEM))
if block == nil {
return fmt.Errorf("failed to parse certificate PEM")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return fmt.Errorf("failed to parse certificate: %v", err.Error())
}
opts := x509.VerifyOptions{
DNSName: name,
Roots: roots,
}
if _, err := cert.Verify(opts); err != nil {
return fmt.Errorf("failed to verify certificate: %v", err.Error())
}
return nil
}
DISCLAIMER: I reorganized it as a function and removed the panics for error handling. The code is otherwise unchanged from the example in the official documentation.