Files
verify/backend/internal/protect/pfx_test.go
hermes b275de31a7
Docker Build / Build and Push Docker Image (push) Successful in 59s
Docker Build / Deploy to Server (push) Successful in 3s
feat(protect): 正确处理一个 pfx 里有多张证书的情况
用户问:我的 pfx 可能一个文件包含很多个证书,能处理吗?
实测三种形态,行为全部对齐签名工具(osslsigncode / OpenSSL PKCS12_parse):

1) 单身份(1 证书 + 1 私钥):普通情况。
2) 链式(叶子 + 中间 CA + 根,证书多但私钥一把):这是好事,签名会把整条链
   写进去,验签更容易过。原来「取第一个证书当签名证书」的做法在这里是错的
   —— 链包里第一张可能是中间 CA。改为按「公钥与私钥配对」认叶子证书。
3) 多身份(一个文件里好几套 私钥+证书):签名工具只会用第一套,原来完全没提示。
   现在上传时就解析出每套身份(序号/主题/到期),库里存 cert_count / key_count,
   列表显示「2 张 / 2 套私钥」,加壳页选中时明确提示「仅使用第一套(CN=…)」。

其它:
- 只有证书没有私钥的 pfx 直接拒(原来会存下来,直到加壳时才炸),报错翻成人话
- 解析全部纯 Go(go-pkcs12 + 自解析 PKCS#1/SEC1),因为生产镜像是 Alpine 没有 openssl CLI
- 签名证书列表新增「证书数」列;schema 补 cert_count/key_count

实测(keytool 造 2 套私钥 p12、openssl 造 3 张链式 pfx、cert-only pfx):
- 单证书 → 1 张 / 1 把
- 链式   → 3 张 / 1 把,签名证书正确识别为叶子;osslsigncode verify 产物里
           同时含 Leaf Signer 与 Test Root CA(链完整)
- 多身份 → 2 张 / 2 把,身份列表 Signer A + Signer B;实际签名者为 Signer A,
           与面板报告一致(不是按到期时间瞎排序)
- 只有证书 → 400「这个文件里只有证书、没有私钥(不是标准 pfx),签不了名」
2026-11-22 11:21:11 +08:00

63 lines
1.9 KiB
Go

package protect
import (
"os"
"testing"
)
// 用真实文件验证三种 pfx 形态的识别结果。
// 依赖 /tmp/pfxlab 下的样本(单证书 / 链式 / 多身份),缺失则跳过。
func TestParsePFXShapes(t *testing.T) {
cases := []struct {
file string
pw string
certCount int
keyCount int
wantSubstr string
}{
{"/tmp/pfxlab/single.pfx", "testpass123", 1, 1, "Leaf Signer"},
{"/tmp/pfxlab/chain.pfx", "testpass123", 3, 1, "Leaf Signer"},
{"/tmp/pfxlab/multi.p12", "testpass123", 2, 2, "Signer"},
}
for _, c := range cases {
data, err := os.ReadFile(c.file)
if err != nil {
t.Logf("跳过 %s(样本不存在)", c.file)
continue
}
info, err := ParsePFX(data, c.pw)
if err != nil {
t.Fatalf("%s 解析失败: %v", c.file, err)
}
t.Logf("%s → 证书 %d 张 / 私钥 %d 把 / 身份 %d 套 / 实际签名=%q / 说明=%q",
c.file, info.CertCount, info.KeyCount, len(info.Identities), info.Signing.Subject, info.Note)
if info.CertCount != c.certCount {
t.Errorf("%s 证书数 = %d, 期望 %d", c.file, info.CertCount, c.certCount)
}
if info.KeyCount != c.keyCount {
t.Errorf("%s 私钥数 = %d, 期望 %d", c.file, info.KeyCount, c.keyCount)
}
if info.Signing.Subject == "" {
t.Errorf("%s 没认到签名证书", c.file)
}
}
}
// 只有证书没有私钥的文件必须被标出来(不能用它签名)
func TestParsePFXCertOnly(t *testing.T) {
data, err := os.ReadFile("/tmp/pfxlab/certonly.pfx")
if err != nil {
t.Skip("样本不存在")
}
info, err := ParsePFX(data, "testpass123")
if err != nil {
// 有些实现直接报错,也算识别出来了
t.Logf("cert-only 直接报错(可接受): %v", err)
return
}
t.Logf("cert-only → 证书 %d / 私钥 %d / 说明=%q", info.CertCount, info.KeyCount, info.Note)
if info.KeyCount != 0 {
t.Errorf("私钥数应为 0,实得 %d", info.KeyCount)
}
}