I have generated self-signed certificate via next command:
/bin/bash -c 'openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 5 -nodes
And check the certificate, it's valid for the next 5 days.
I need to write the script which will just check the expiration date of this certificate, but unfortunately it's cannot validate it. Could you please just maybe put on correct flow?
My program:
package main
import (
"crypto/x509"
"encoding/pem"
"fmt"
)
func main() {
const certPEM = `
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----`
block, _ := pem.Decode([]byte(certPEM))
if block == nil {
panic("failed to parse certificate PEM")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
panic("failed to parse certificate: " + err.Error())
}
opts := x509.VerifyOptions{
DNSName: "test.com",
}
if _, err := cert.Verify(opts); err != nil {
panic("failed to verify certificate: " + err.Error())
}
fmt.Println("correct")
}
The next error I have:
panic: failed to verify certificate: x509: certificate signed by unknown authority
Since it is a self-signed certificate, you can use the certificate as one of the roots to verify it:
// Create the cert pool
roots := x509.NewCertPool()
ok := roots.AppendCertsFromPEM([]byte(certPEM))
if !ok {
panic("failed to parse root certificate")
}
...
// Use the pool in the verify options:
opts := x509.VerifyOptions{
DNSName: "test.com",
Roots: roots,
}
...
Without passing a pool, Go will use the system pool which will definitely not work. By adding the certificate itself, a valid path can be built to a trusted root. It will also validate the rest of the certificate (name and valid time range).
This is explained in more detail in the docs for Certificate.Verify.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With