go - 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
解决方案
由于它是自签名证书,您可以使用该证书作为根之一来验证它:
// 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的文档中有更详细的解释。
推荐阅读
- sql - 如何在 VB.net 中创建 SQL 数据库?
- excel - VBA Excel递归文件夹搜索停止
- types - 下面的 OCaml 行是做什么的: type reply = (string * string list * string, error_t) result;;?
- android - 如何导出我的手机在过去 8 小时内的活动?
- node.js - 电子打包机 win32 不打开窗口
- node.js - Mocha - 循环遍历在 before() 中初始化的数组失败
- amazon-iam - AWS IAM:这是基于资源或身份的策略吗?
- c# - Hangfire.AspNetCore.dll 中出现“System.StackOverflowException”类型的未处理异常
- react-router - React-router 链接在共享时被转义
- android - 在 onClickListener 中关闭 Anko 对话框