57 lines
1.4 KiB
Go
57 lines
1.4 KiB
Go
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 应返回错误")
|
|
}
|
|
}
|