Files
4566704 f120ab24ed feat(certx): go-hua/ssl 迁入并更名 certx(证书/私钥工具)
- 原包名 ssl 与协议名混淆, 实为 x509 证书解析校验与自签生成, 更名 certx
- 附测试、examples/certx 例程与包 README
2026-09-20 12:37:10 +08:00

41 lines
1.2 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// certx 包示例:自签证书生成与解析、私钥解析、证书私钥匹配校验(全程内存操作)
package main
import (
"fmt"
"git.zeroonesoft.cn/golib/zogo/certx"
)
func main() {
// 生成自签名证书(RSA 2048,有效期 10 年)
certPEM, keyPEM, err := certx.CreateCertificate("go-hua.example.com", []string{"go-hua.example.com", "localhost"})
if err != nil {
panic(err)
}
fmt.Printf("证书 PEM: %d 字节, 私钥 PEM: %d 字节\n", len(certPEM), len(keyPEM))
// 解析证书
cert, err := certx.ParseCertificate(certPEM)
if err != nil {
panic(err)
}
fmt.Println("主题:", cert.Subject.CommonName)
fmt.Println("DNS 名称:", cert.DNSNames)
fmt.Println("有效期至:", cert.NotAfter.Format("2006-01-02"))
// 解析私钥(自动尝试 PKCS1 / PKCS8 / EC)
key, err := certx.ParsePrivateKey(keyPEM)
if err != nil {
panic(err)
}
fmt.Printf("私钥类型: %T\n", key)
// 校验证书与私钥是否匹配
fmt.Println("证书私钥匹配:", certx.VerifyPrivateKey(cert, keyPEM) == nil)
// 实际 TLS 服务中的用法:
// certPair, _ := tls.X509KeyPair(certPEM, keyPEM)
// tls.NewListener(listener, &tls.Config{Certificates: []tls.Certificate{certPair}})
}