feat(protect): 一个 pfx 里的多套签名身份全部解析出来,任选一套签
之前只解析出「文件里第一套」,其余几套只能在提示里看到名字、用不上。 现在上传时按套拆开,每套单独编码成一份单身份 pfx,各建一条记录, 加壳页任选一条即可真的用那一套签名。 实现(internal/protect/pfx.go 新增 SplitPFX): - 第一遍按文件顺序给每把私钥配证书(公钥比对),记下哪些证书是身份证书 - 链 = 没有配到私钥的证书(中间 CA / 根)。刻意不把「另一套身份的叶子证书」 塞进链里 —— 实测那样做产物证书表里会混进 Signer A,看起来像被 A 签过 - 每套用 pkcs12.Modern.Encode 重新打包(AES 失败退 LegacyRC2),口令沿用原口令 - 链式包(1 套私钥 + N 张 CA)仍是一条记录,不会被误拆 后端 signprofiles.go:抽出 createProfile(),多套时循环建记录,命名 「<原名> · 第N套 <CN>」,响应回 created/items;只有证书没私钥仍是 400。 前端:上传成功提示区分单套/多套(多套时列出每套 subject)。 实测(keytool 造 2 套私钥 p12): - 上传 → 2 条记录(第1套 Signer A / 第2套 Signer B) - 用第2套签名 → osslsigncode verify 产物证书表全是 Signer B,摘要一致 (改之前:无论选谁都只能签出 Signer A) - 链式 pfx → 仍 1 条记录,产物含 Leaf Signer + Test Root CA - 只有证书 → 400 人话报错
This commit is contained in:
@@ -160,3 +160,105 @@ func parseAnyPrivateKey(der []byte) (interface{}, error) {
|
||||
}
|
||||
return nil, fmt.Errorf("无法识别的私钥编码")
|
||||
}
|
||||
|
||||
// SplitIdentity 一套可签名的身份,以及把它单独编码成 pfx 的结果。
|
||||
type SplitIdentity struct {
|
||||
Index int
|
||||
Subject string
|
||||
NotAfter time.Time
|
||||
Expired bool
|
||||
ChainLen int // 附带的链上证书张数
|
||||
PFX []byte // 只有这一套私钥+证书(+链)的 pfx,口令同原文件
|
||||
}
|
||||
|
||||
// SplitPFX 把一个 pfx 里的每套「私钥+证书」拆成独立的单身份 pfx。
|
||||
//
|
||||
// 为什么需要拆:osslsigncode / OpenSSL 的 PKCS12_parse 只会取文件里第一套,
|
||||
// 想用第二套签名就必须给它一个只含第二套的文件。拆的时候顺带把其余证书
|
||||
// 作为链带进去,签名产物仍然有完整链。
|
||||
func SplitPFX(data []byte, password string) ([]SplitIdentity, error) {
|
||||
blocks, err := pkcs12.ToPEM(data, password)
|
||||
if err != nil && password != "" {
|
||||
blocks, err = pkcs12.ToPEM(data, "")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析 pfx 失败: %w", err)
|
||||
}
|
||||
|
||||
var certs []*x509.Certificate
|
||||
var keys []interface{}
|
||||
for _, b := range blocks {
|
||||
switch b.Type {
|
||||
case "CERTIFICATE":
|
||||
if c, e := x509.ParseCertificate(b.Bytes); e == nil {
|
||||
certs = append(certs, c)
|
||||
}
|
||||
case "PRIVATE KEY", "RSA PRIVATE KEY", "EC PRIVATE KEY":
|
||||
if k, e := parseAnyPrivateKey(b.Bytes); e == nil {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(keys) == 0 {
|
||||
return nil, fmt.Errorf("文件里没有私钥")
|
||||
}
|
||||
|
||||
// 第一遍:按文件顺序给每把私钥配证书,记下哪些证书是「身份证书」
|
||||
type pairing struct {
|
||||
key interface{}
|
||||
cert *x509.Certificate
|
||||
idx int
|
||||
}
|
||||
var pairs []pairing
|
||||
used := make(map[int]bool)
|
||||
for _, k := range keys {
|
||||
pub, ok := publicOf(k)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
for i, c := range certs {
|
||||
if used[i] {
|
||||
continue
|
||||
}
|
||||
if publicEqual(pub, c.PublicKey) {
|
||||
pairs = append(pairs, pairing{key: k, cert: c, idx: i})
|
||||
used[i] = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 链 = 没有配到私钥的证书(中间 CA / 根)。
|
||||
// 注意不能把「另一套身份的叶子证书」塞进链里 —— 那会让产物看起来像是
|
||||
// 也被 Signer A 签过(实测出现过 Signer A 混在证书表里的情况)。
|
||||
var chain []*x509.Certificate
|
||||
for i, c := range certs {
|
||||
if !used[i] {
|
||||
chain = append(chain, c)
|
||||
}
|
||||
}
|
||||
|
||||
var out []SplitIdentity
|
||||
for _, p := range pairs {
|
||||
blob, eerr := pkcs12.Modern.Encode(p.key, p.cert, chain, password)
|
||||
if eerr != nil {
|
||||
// AES 编码失败时退到兼容模式(老工具只认 RC2/3DES)
|
||||
blob, eerr = pkcs12.LegacyRC2.Encode(p.key, p.cert, chain, password)
|
||||
}
|
||||
if eerr != nil {
|
||||
return nil, fmt.Errorf("重新打包第 %d 套证书失败: %w", len(out)+1, eerr)
|
||||
}
|
||||
out = append(out, SplitIdentity{
|
||||
Index: len(out) + 1,
|
||||
Subject: p.cert.Subject.String(),
|
||||
NotAfter: p.cert.NotAfter,
|
||||
Expired: p.cert.NotAfter.Before(time.Now()),
|
||||
ChainLen: len(chain),
|
||||
PFX: blob,
|
||||
})
|
||||
}
|
||||
if len(out) == 0 {
|
||||
return nil, fmt.Errorf("没有找到私钥与证书的配对")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
@@ -4,12 +4,14 @@ package admin
|
||||
// 供加壳产物重签时取用;任何响应都不回证书内容与口令。
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"verification-platform-backend/internal/database"
|
||||
"verification-platform-backend/internal/model"
|
||||
@@ -31,6 +33,54 @@ func SetupSignProfileRoutes(r *gin.RouterGroup) {
|
||||
|
||||
// HandleCreateSignProfile 上传证书(multipart)
|
||||
// 字段:platform(windows|ios)、name、cert(文件, .pfx/.p12)、password、profile(iOS 的 .mobileprovision)
|
||||
// createProfile 建一条证书记录并把加密后的文件落盘。
|
||||
// 拆包(一个 pfx 多套身份)时每套都会调一次,所以抽出来。
|
||||
func createProfile(userID uint, platform, name, certFormat string, certData []byte, password string,
|
||||
subject string, notAfter *time.Time, certCount, keyCount int, profileData []byte) (model.SignProfile, error) {
|
||||
|
||||
sp := model.SignProfile{
|
||||
UserID: userID,
|
||||
Platform: platform,
|
||||
Name: name,
|
||||
CertFormat: certFormat,
|
||||
Subject: subject,
|
||||
NotAfter: notAfter,
|
||||
CertCount: certCount,
|
||||
KeyCount: keyCount,
|
||||
Status: "active",
|
||||
}
|
||||
if err := database.DB.Create(&sp).Error; err != nil {
|
||||
return sp, err
|
||||
}
|
||||
dir := protect.ProfileDir(sp.ID)
|
||||
sp.CertPath = filepath.Join(dir, "cert.enc")
|
||||
sp.PassPath = filepath.Join(dir, "pass.enc")
|
||||
|
||||
fail := func(err error) (model.SignProfile, error) {
|
||||
os.RemoveAll(dir)
|
||||
database.DB.Delete(&sp)
|
||||
return sp, err
|
||||
}
|
||||
if err := protect.WriteEncrypted(sp.CertPath, certData); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
if password != "" {
|
||||
if err := protect.WriteEncrypted(sp.PassPath, []byte(password)); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
}
|
||||
if len(profileData) > 0 {
|
||||
sp.ProfilePath = filepath.Join(dir, "profile.enc")
|
||||
if err := protect.WriteEncrypted(sp.ProfilePath, profileData); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
}
|
||||
if err := database.DB.Save(&sp).Error; err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
return sp, nil
|
||||
}
|
||||
|
||||
func HandleCreateSignProfile(c *gin.Context) {
|
||||
userID := c.GetUint("user_id")
|
||||
|
||||
@@ -97,71 +147,76 @@ func HandleCreateSignProfile(c *gin.Context) {
|
||||
response.ParamError(c, "这个文件里只有证书、没有私钥,签不了名。请导出带私钥的 .pfx/.p12")
|
||||
return
|
||||
}
|
||||
subject, notAfter := pfx.Signing.Subject, &pfx.Signing.NotAfter
|
||||
certFormat := strings.TrimPrefix(ext, ".")
|
||||
|
||||
sp := model.SignProfile{
|
||||
UserID: userID,
|
||||
Platform: platform,
|
||||
Name: name,
|
||||
CertFormat: strings.TrimPrefix(ext, "."),
|
||||
Subject: subject,
|
||||
NotAfter: notAfter,
|
||||
CertCount: pfx.CertCount,
|
||||
KeyCount: pfx.KeyCount,
|
||||
Status: "active",
|
||||
}
|
||||
if err := database.DB.Create(&sp).Error; err != nil {
|
||||
response.InternalError(c, "创建证书记录失败")
|
||||
// 一个 pfx 里可能有多套「私钥+证书」。签名工具只会用第一套,所以这里
|
||||
// 按套拆开、每套单独建一条记录 —— 这样用户能在加壳页任选一套签名,
|
||||
// 而不是只能被动接受"文件里的第一套"。
|
||||
ids, serr := protect.SplitPFX(certData, password)
|
||||
if serr != nil {
|
||||
response.InternalError(c, "拆分证书失败:"+serr.Error())
|
||||
return
|
||||
}
|
||||
|
||||
dir := protect.ProfileDir(sp.ID)
|
||||
sp.CertPath = filepath.Join(dir, "cert.enc")
|
||||
sp.PassPath = filepath.Join(dir, "pass.enc")
|
||||
if err := protect.WriteEncrypted(sp.CertPath, certData); err != nil {
|
||||
database.DB.Delete(&sp)
|
||||
response.InternalError(c, "保存证书失败")
|
||||
return
|
||||
type created struct {
|
||||
ID uint `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Subject string `json:"subject"`
|
||||
NotAfter *time.Time `json:"not_after"`
|
||||
Expired bool `json:"expired"`
|
||||
ChainLen int `json:"chain_len"`
|
||||
CertCount int `json:"cert_count"`
|
||||
KeyCount int `json:"key_count"`
|
||||
}
|
||||
if password != "" {
|
||||
if err := protect.WriteEncrypted(sp.PassPath, []byte(password)); err != nil {
|
||||
os.RemoveAll(dir)
|
||||
database.DB.Delete(&sp)
|
||||
response.InternalError(c, "保存口令失败")
|
||||
made := make([]created, 0, len(ids))
|
||||
for _, it := range ids {
|
||||
label := name
|
||||
if len(ids) > 1 {
|
||||
label = fmt.Sprintf("%s · 第%d套 %s", name, it.Index, shortCN(it.Subject))
|
||||
}
|
||||
na := it.NotAfter
|
||||
sp, cerr := createProfile(userID, platform, label, certFormat, it.PFX, password,
|
||||
it.Subject, &na, it.ChainLen+1, 1, profileData)
|
||||
if cerr != nil {
|
||||
// 已经建成功的保留,把失败原因说清楚
|
||||
response.InternalError(c, "保存第 "+strconv.Itoa(it.Index)+" 套证书失败:"+cerr.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
if len(profileData) > 0 {
|
||||
sp.ProfilePath = filepath.Join(dir, "profile.enc")
|
||||
if err := protect.WriteEncrypted(sp.ProfilePath, profileData); err != nil {
|
||||
os.RemoveAll(dir)
|
||||
database.DB.Delete(&sp)
|
||||
response.InternalError(c, "保存描述文件失败")
|
||||
return
|
||||
}
|
||||
}
|
||||
if err := database.DB.Save(&sp).Error; err != nil {
|
||||
response.InternalError(c, "保存证书信息失败")
|
||||
return
|
||||
made = append(made, created{
|
||||
ID: sp.ID, Name: sp.Name, Subject: sp.Subject, NotAfter: sp.NotAfter,
|
||||
Expired: it.Expired, ChainLen: it.ChainLen, CertCount: it.ChainLen + 1, KeyCount: 1,
|
||||
})
|
||||
}
|
||||
|
||||
response.SuccessWithMessage(c, "证书已加密保存", gin.H{
|
||||
"id": sp.ID,
|
||||
"platform": sp.Platform,
|
||||
"name": sp.Name,
|
||||
"format": sp.CertFormat,
|
||||
"has_profile": sp.ProfilePath != "",
|
||||
msg := "证书已加密保存"
|
||||
if len(made) > 1 {
|
||||
msg = fmt.Sprintf("这个文件里含 %d 套证书,已分别保存为 %d 条记录,可在加壳时任选一套", len(made), len(made))
|
||||
}
|
||||
response.SuccessWithMessage(c, msg, gin.H{
|
||||
"created": len(made),
|
||||
"items": made,
|
||||
"cert_count": pfx.CertCount,
|
||||
"key_count": pfx.KeyCount,
|
||||
"identities": pfx.Identities,
|
||||
"note": pfx.Note,
|
||||
"fingerprint": protect.Fingerprint(certData),
|
||||
"subject": sp.Subject,
|
||||
"not_after": sp.NotAfter,
|
||||
// 这个 pfx 里装了什么:证书几张、私钥几把、以及说明
|
||||
"cert_count": pfx.CertCount,
|
||||
"key_count": pfx.KeyCount,
|
||||
"note": pfx.Note,
|
||||
"identities": pfx.Identities,
|
||||
})
|
||||
}
|
||||
|
||||
// shortCN 从 "CN=xxx,O=yyy" 里抽出 CN,用于给拆出来的记录起名字
|
||||
func shortCN(subject string) string {
|
||||
for _, part := range strings.Split(subject, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if strings.HasPrefix(part, "CN=") {
|
||||
return strings.TrimPrefix(part, "CN=")
|
||||
}
|
||||
}
|
||||
if subject == "" {
|
||||
return "证书"
|
||||
}
|
||||
return subject
|
||||
}
|
||||
|
||||
// HandleListSignProfiles 列表(不含任何敏感字段)
|
||||
func HandleListSignProfiles(c *gin.Context) {
|
||||
userID := c.GetUint("user_id")
|
||||
|
||||
@@ -79,8 +79,18 @@ async function submit() {
|
||||
if (form.value.platform === 'ios' && profileFile.value)
|
||||
fd.append('profile', profileFile.value)
|
||||
|
||||
await api.postFormData('/dev/sign-profiles', fd)
|
||||
toast.success(t('admin.signProfiles.uploaded'))
|
||||
// 一个 pfx 里可能含多套「私钥+证书」,后端会按套拆成多条记录,
|
||||
// 这里要说清楚拆出了几条,否则用户只看到列表多了一堆名字相近的条目
|
||||
const resp: any = await api.postFormData('/dev/sign-profiles', fd)
|
||||
const items = resp?.data?.items || []
|
||||
if (items.length > 1) {
|
||||
toast.success(t('admin.signProfiles.uploadedSplit', { n: items.length }), {
|
||||
description: items.map((i: any) => `第${items.indexOf(i) + 1}套 ${i.subject}`).join(' / '),
|
||||
})
|
||||
}
|
||||
else {
|
||||
toast.success(t('admin.signProfiles.uploaded'))
|
||||
}
|
||||
form.value.name = ''
|
||||
form.value.password = ''
|
||||
certFile.value = null
|
||||
|
||||
@@ -2678,7 +2678,8 @@
|
||||
"noExpiry": "No expiry info",
|
||||
"expired": "Expired",
|
||||
"daysLeft": "days left",
|
||||
"colCerts": "Certificates"
|
||||
"colCerts": "Certificates",
|
||||
"uploadedSplit": "Parsed {n} identities from this file; {n} records created. Pick any one when protecting."
|
||||
}
|
||||
},
|
||||
"auth": {
|
||||
|
||||
@@ -2697,7 +2697,8 @@
|
||||
"noExpiry": "无到期信息",
|
||||
"expired": "已过期",
|
||||
"daysLeft": "天后过期",
|
||||
"colCerts": "证书数"
|
||||
"colCerts": "证书数",
|
||||
"uploadedSplit": "已从该文件解析出 {n} 套证书,分别建了 {n} 条记录,加壳时可任选一套"
|
||||
}
|
||||
},
|
||||
"auth": {
|
||||
|
||||
Reference in New Issue
Block a user