首页 > 解决方案 > Check validity of SSL self-signed certificate

问题描述

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

标签: gossl

解决方案


由于它是自签名证书,您可以使用该证书作为根之一来验证它:

  // 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,
  }

  ...

如果不通过池,Go 将使用系统池,这肯定是行不通的。通过添加证书本身,可以构建到受信任根的有效路径。它还将验证证书的其余部分(名称和有效时间范围)。

这在Certificate.Verify的文档中有更详细的解释。


推荐阅读