feat(certx): go-hua/ssl 迁入并更名 certx(证书/私钥工具)
- 原包名 ssl 与协议名混淆, 实为 x509 证书解析校验与自签生成, 更名 certx - 附测试、examples/certx 例程与包 README
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
package certx
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestCreateAndParseCertificate(t *testing.T) {
|
||||
certPEM, keyPEM, err := CreateCertificate("test.example.com", []string{"test.example.com", "localhost"})
|
||||
if err != nil {
|
||||
t.Fatalf("CreateCertificate: %v", err)
|
||||
}
|
||||
|
||||
// PEM 格式校验
|
||||
if !strings.Contains(string(certPEM), "BEGIN CERTIFICATE") {
|
||||
t.Error("证书 PEM 格式错误")
|
||||
}
|
||||
if !strings.Contains(string(keyPEM), "PRIVATE KEY") {
|
||||
t.Error("私钥 PEM 格式错误")
|
||||
}
|
||||
|
||||
// 解析证书
|
||||
cert, err := ParseCertificate(certPEM)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseCertificate: %v", err)
|
||||
}
|
||||
if cert.Subject.CommonName != "test.example.com" {
|
||||
t.Errorf("CommonName = %q", cert.Subject.CommonName)
|
||||
}
|
||||
if len(cert.DNSNames) != 2 {
|
||||
t.Errorf("DNSNames = %v, want 2 项", cert.DNSNames)
|
||||
}
|
||||
if !time.Now().Before(cert.NotAfter) {
|
||||
t.Error("证书应未过期")
|
||||
}
|
||||
|
||||
// 解析私钥
|
||||
if _, err := ParsePrivateKey(keyPEM); err != nil {
|
||||
t.Fatalf("ParsePrivateKey: %v", err)
|
||||
}
|
||||
|
||||
// 证书与私钥匹配
|
||||
if err := VerifyPrivateKey(cert, keyPEM); err != nil {
|
||||
t.Errorf("证书私钥应匹配: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseInvalidPem(t *testing.T) {
|
||||
if _, err := ParseCertificate([]byte("not a pem")); err == nil {
|
||||
t.Error("非法 PEM 应返回错误")
|
||||
}
|
||||
if _, err := ParsePrivateKey([]byte("not a pem")); err == nil {
|
||||
t.Error("非法 PEM 应返回错误")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user