验证SSL自签名证书的有效性。

4

我通过下面的命令生成了自签名证书:

/bin/bash -c 'openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 5 -nodes

请检查证书,它在接下来的5天内有效。

我需要编写一个脚本,只检查此证书的过期日期,但不幸的是无法验证它。 能否请您提供正确的流程呢?

我的程序:

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")
}

我遇到的下一个错误是:

恐慌:验证证书失败:x509:证书由未知机构签名

1个回答

3

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

  // 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文档中找到。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接