【问题标题】:Check validity of SSL self-signed certificate检查 SSL 自签名证书的有效性
【发布时间】:2020-08-09 19:18:18
【问题描述】:

我已经通过下一条命令生成了自签名证书:

/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:证书由 未知权限

【问题讨论】:

    标签: go ssl


    【解决方案1】:

    由于是自签名证书,所以可以将证书作为根之一进行验证:

      // 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 的文档中对此进行了更详细的解释。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-01
      • 2015-06-18
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-24
      相关资源
      最近更新 更多