diff --git a/backend/internal/protect/pfx.go b/backend/internal/protect/pfx.go index cfdfb82..54ef4cf 100644 --- a/backend/internal/protect/pfx.go +++ b/backend/internal/protect/pfx.go @@ -347,6 +347,12 @@ func ParsePFX(data []byte, password string) (PFXInfo, error) { // 想用第二套签名就必须给它一个只含第二套的文件。拆的时候顺带把真正的 // 链证书(配不到私钥的那些)带进去,签名产物仍然有完整链。 func SplitPFX(data []byte, password string) ([]SplitIdentity, error) { + return SplitPFXWithPassword(data, password, "") // 空 = 沿用原口令 +} + +// SplitPFXWithPassword 同 SplitPFX,但可以用 newPassword 重新设置导出文件的口令。 +// 批量导出时用户会指定一个统一口令,这里负责重打包。 +func SplitPFXWithPassword(data []byte, password, newPassword string) ([]SplitIdentity, error) { m, err := loadMaterial(data, password) if err != nil { return nil, err @@ -398,12 +404,16 @@ func SplitPFX(data []byte, password string) ([]SplitIdentity, error) { } } + outPW := m.pw + if newPassword != "" { + outPW = newPassword + } var out []SplitIdentity for _, p := range pairs { - blob, eerr := pkcs12.Modern.Encode(p.key, p.cert, chain, m.pw) + blob, eerr := pkcs12.Modern.Encode(p.key, p.cert, chain, outPW) if eerr != nil { // AES 编码失败时退到兼容模式(老工具只认 RC2/3DES) - blob, eerr = pkcs12.LegacyRC2.Encode(p.key, p.cert, chain, m.pw) + blob, eerr = pkcs12.LegacyRC2.Encode(p.key, p.cert, chain, outPW) } if eerr != nil { return nil, &PFXError{ diff --git a/backend/internal/router/admin/certexport.go b/backend/internal/router/admin/certexport.go new file mode 100644 index 0000000..f0c9268 --- /dev/null +++ b/backend/internal/router/admin/certexport.go @@ -0,0 +1,197 @@ +package admin + +// 批量导出证书身份:把一个 pfx 里选中的每套「私钥+证书」重新打包成独立的 +// pfx(用用户指定的统一口令),再打成一个 zip 下载。 +// +// 为什么需要:一个驱动签名包里可能装几十套证书,用户往往要拿去 Windows 上 +// 用 signtool 单独试签,一个个导太麻烦。这里按套导出,文件名带序号和 CN, +// 一眼能对上是哪张证书。 + +import ( + "archive/zip" + "bytes" + "fmt" + "regexp" + "strconv" + "strings" + "time" + + "github.com/gin-gonic/gin" + + "verification-platform-backend/internal/database" + "verification-platform-backend/internal/model" + "verification-platform-backend/internal/protect" + "verification-platform-backend/pkg/response" +) + +// 文件名里不能出现的字符 +var unsafeName = regexp.MustCompile(`[\\/:*?"<>|\r\n\t]+`) + +// HandleExportIdentities 批量导出选中身份 +// +// POST /dev/sign-profiles/:id/export +// +// { "identities": [1,2,3] 或 "all", "password": "导出用的口令", +// "skip_revoked": true, "check_revoked": true } +// +// 响应:application/zip,内含 <序号>_.pfx +func HandleExportIdentities(c *gin.Context) { + userID := c.GetUint("user_id") + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + response.ParamError(c, "证书 ID 不合法") + return + } + + var req struct { + Identities []int `json:"identities"` + All bool `json:"all"` + Password string `json:"password"` + SkipRevoked bool `json:"skip_revoked"` + CheckRevoked bool `json:"check_revoked"` + } + if err := c.ShouldBindJSON(&req); err != nil { + response.ParamError(c, "参数格式不对") + return + } + if req.Password == "" { + response.ParamError(c, "请设置导出文件的密码(导出的是带私钥的 pfx,必须有口令)") + return + } + if len(req.Password) > 64 { + response.ParamError(c, "密码过长(最多 64 字符)") + return + } + + var sp model.SignProfile + if err := database.DB.Where("id = ? AND user_id = ?", id, userID).First(&sp).Error; err != nil { + response.NotFound(c, "证书不存在") + return + } + certData, err := protect.ReadEncrypted(sp.CertPath) + if err != nil { + response.InternalError(c, "读取证书失败") + return + } + password := "" + if b, e := protect.ReadEncrypted(sp.PassPath); e == nil { + password = string(b) + } + + // 用新口令重打包所有身份 + all, serr := protect.SplitPFXWithPassword(certData, password, req.Password) + if serr != nil { + response.InternalError(c, "导出失败:"+serr.Error()) + return + } + if len(all) == 0 { + response.ParamError(c, "这个文件里没有可导出的身份") + return + } + + // 选中哪些 + want := map[int]bool{} + for _, i := range req.Identities { + want[i] = true + } + + // 需要先知道吊销状态(用户可要求跳过已吊销) + var details []protect.IdentityDetail + if req.CheckRevoked || req.SkipRevoked { + if d, derr := protect.ParseIdentitiesFull(certData, password); derr == nil { + details = d + } + } + revokedIdx := map[int]bool{} + ban := localBanMap() + for _, d := range details { + if protect.CheckRevocation(d.Cert, d.Issuer).Status == protect.RevokeRevoked { + revokedIdx[d.Index] = true + continue + } + if protect.BanState(d.Cert, ban).Status == protect.RevokeRevoked { + revokedIdx[d.Index] = true + } + } + + buf := &bytes.Buffer{} + zw := zip.NewWriter(buf) + added := 0 + skipped := 0 + for _, it := range all { + if !req.All && len(want) > 0 && !want[it.Index] { + continue + } + if req.SkipRevoked && revokedIdx[it.Index] { + skipped++ + continue + } + name := fmt.Sprintf("%03d_%s.pfx", it.Index, safeFileStem(cnFromSubject(it.Subject))) + w, werr := zw.Create(name) + if werr != nil { + response.InternalError(c, "打包失败:"+werr.Error()) + return + } + if _, werr = w.Write(it.PFX); werr != nil { + response.InternalError(c, "写包失败:"+werr.Error()) + return + } + added++ + } + // 附一份清单,方便核对导出了哪些、口令是什么(口令只写在包里,不进日志) + var readme strings.Builder + readme.WriteString("证书批量导出\n") + readme.WriteString("导出时间:" + time.Now().Format("2006-01-02 15:04:05") + "\n") + readme.WriteString("来源记录:" + sp.Name + "\n") + readme.WriteString("文件口令:" + req.Password + "\n") + if skipped > 0 { + readme.WriteString(fmt.Sprintf("已跳过 %d 套(已吊销/已拉黑)\n", skipped)) + } + readme.WriteString("\n用法(Windows):\n") + readme.WriteString(" signtool sign /f 001_xxx.pfx /p 口令 /fd sha256 /tr http://timestamp.digicert.com /td sha256 程序.exe\n") + readme.WriteString(" 驱动加 -ac 交叉证书:/ac MSCV-VSClass3.cer\n") + if w, werr := zw.Create("README.txt"); werr == nil { + w.Write([]byte(readme.String())) + } + if err := zw.Close(); err != nil { + response.InternalError(c, "打包失败:"+err.Error()) + return + } + if added == 0 { + response.ParamError(c, "没有可导出的身份(可能都被跳过或没选中)") + return + } + + fname := fmt.Sprintf("%s_身份导出_%s.zip", safeFileStem(cnFromSubject(sp.Subject)), time.Now().Format("20060102_150405")) + c.Header("Content-Type", "application/zip") + c.Header("Content-Disposition", "attachment; filename=\""+fname+"\"") + c.Header("X-Exported", strconv.Itoa(added)) + c.Data(200, "application/zip", buf.Bytes()) +} + +// cnFromSubject 从 "C=CN, O=xx, CN=yyy" 里取 CN +func cnFromSubject(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 +} + +// safeFileStem 把 CN 变成安全的文件名片段 +func safeFileStem(s string) string { + s = unsafeName.ReplaceAllString(s, "_") + s = strings.TrimSpace(s) + if len(s) > 60 { + s = s[:60] + } + if s == "" || s == "." || s == ".." { + s = "证书" + } + return s +} diff --git a/backend/internal/router/admin/signprofiles.go b/backend/internal/router/admin/signprofiles.go index 645caad..1989e1c 100644 --- a/backend/internal/router/admin/signprofiles.go +++ b/backend/internal/router/admin/signprofiles.go @@ -29,6 +29,7 @@ func SetupSignProfileRoutes(r *gin.RouterGroup) { g.GET("", HandleListSignProfiles) g.GET("/:id", HandleGetSignProfile) g.GET("/:id/identities", HandleListIdentities) + g.POST("/:id/export", HandleExportIdentities) g.GET("/blacklist", HandleListBlacklist) g.POST("/blacklist", HandleAddBlacklist) g.DELETE("/blacklist/:id", HandleDeleteBlacklist) @@ -100,10 +101,9 @@ func HandleCreateSignProfile(c *gin.Context) { response.ParamError(c, err.Error()) return } + // 名称不让用户填:显示名就用证书本身的 CN,避免「自己起的标签」和 + // 「实际签名者」两套名字对不上。解析完证书后再回填(见下面 cnName)。 name := strings.TrimSpace(c.PostForm("name")) - if name == "" { - name = "未命名证书" - } password := c.PostForm("password") fh, err := c.FormFile("cert") @@ -178,6 +178,13 @@ func HandleCreateSignProfile(c *gin.Context) { } certFormat := strings.TrimPrefix(ext, ".") + // 显示名 = 证书 CN。用户填的名字只当备注,不用它当主显示名。 + if cn := cnFromSubject(pfx.Signing.Subject); cn != "" { + name = cn + } else if name == "" { + name = "未命名证书" + } + // 一个证书文件里可能装几十套「私钥+证书」(驱动签名打包这类文件很常见)。 // 这里**不拆成多条记录**——79 套就建 79 条记录没法用;而是只建一条, // 记下有几套身份,加壳时用 cert_identity 指定用哪一套,签名那一刻才拆。 diff --git a/frontend/src/pages/admin/sign-profiles/components/columns.ts b/frontend/src/pages/admin/sign-profiles/components/columns.ts index 6257a18..eb2326d 100644 --- a/frontend/src/pages/admin/sign-profiles/components/columns.ts +++ b/frontend/src/pages/admin/sign-profiles/components/columns.ts @@ -21,14 +21,7 @@ interface ColumnOptions { export function getColumns(options: ColumnOptions, t: (key: string) => string): ColumnDef[] { return [ - { - accessorKey: 'name', - header: () => t('admin.signProfiles.colName'), - cell: ({ row }) => h('div', { class: 'flex items-center gap-2' }, [ - h(ShieldCheck, { class: 'h-4 w-4 text-emerald-600 dark:text-emerald-400' }), - h('span', { class: 'font-medium' }, row.original.name), - ]), - }, + { // 证书名称(CN):用户填的「名称」只是自己起的标签,真正决定签名者是谁的是 // 证书里的 CN,两个都要能看见 @@ -37,9 +30,12 @@ export function getColumns(options: ColumnOptions, t: (key: string) => string): cell: ({ row }) => { const sub = row.original.subject || '' const cn = sub.split('CN=').pop()?.split(',')[0]?.trim() || sub || '-' - return h('div', { class: 'max-w-[260px] truncate text-xs', title: sub }, cn) + return h('div', { class: 'flex items-center gap-2' }, [ + h(ShieldCheck, { class: 'h-4 w-4 shrink-0 text-emerald-600 dark:text-emerald-400' }), + h('span', { class: 'max-w-[320px] truncate font-medium', title: sub }, cn), + ]) }, - size: 220, + size: 320, }, { accessorKey: 'platform', diff --git a/frontend/src/pages/admin/sign-profiles/index.vue b/frontend/src/pages/admin/sign-profiles/index.vue index 4c73a37..500133c 100644 --- a/frontend/src/pages/admin/sign-profiles/index.vue +++ b/frontend/src/pages/admin/sign-profiles/index.vue @@ -8,6 +8,7 @@ import { BasicPage } from '@/components/global-layout' import type { SignProfile } from '@/pages/admin/sign-profiles/data/schema' import SignProfileDataTable from '@/pages/admin/sign-profiles/components/data-table.vue' +import { BASE_URL } from '@/services/api' import api from '@/services/api' const { t } = useI18n() @@ -18,7 +19,6 @@ const uploading = ref(false) const form = ref({ platform: 'windows' as 'windows' | 'ios', - name: '', password: '', }) const certFile = ref(null) @@ -34,6 +34,10 @@ const identityProfile = ref(null) const identities = ref([]) const identityLoading = ref(false) const checking = ref(false) +const selected = ref([]) +const exporting = ref(false) +const exportPassword = ref('') +const exportSkipRevoked = ref(true) const checkDone = ref(0) async function openIdentities(row: SignProfile) { @@ -111,6 +115,64 @@ function stateClass(info: any) { return 'text-muted-foreground' } +// 勾选 / 全选 / 反选 +function toggleAll(on: boolean) { + selected.value = on ? identities.value.map((i: any) => i.index) : [] +} + +async function exportSelected() { + if (!identityProfile.value) return + const targets = selected.value.length ? selected.value : identities.value.map((i: any) => i.index) + if (!targets.length) { + toast.error(t('admin.signProfiles.nothingToExport')) + return + } + if (!exportPassword.value || exportPassword.value.length < 4) { + toast.error(t('admin.signProfiles.exportPwdHint')) + return + } + exporting.value = true + try { + const token = localStorage.getItem('token') || '' + const resp = await fetch(`${BASE_URL}/dev/sign-profiles/${identityProfile.value.id}/export`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` }, + body: JSON.stringify({ + identities: targets, + all: targets.length === identities.value.length, + password: exportPassword.value, + skip_revoked: exportSkipRevoked.value, + check_revoked: true, + }), + }) + if (!resp.ok) { + let msg = '导出失败' + try { + const j = await resp.json() + msg = j.message || msg + } + catch {} + throw new Error(msg) + } + const blob = await resp.blob() + const url = URL.createObjectURL(blob) + const a = document.createElement('a') + a.href = url + a.download = `证书身份导出_${new Date().toISOString().slice(0, 10)}.zip` + document.body.appendChild(a) + a.click() + a.remove() + URL.revokeObjectURL(url) + toast.success(t('admin.signProfiles.exportDone', { n: targets.length })) + } + catch (e: any) { + toast.error(e?.message || '导出失败') + } + finally { + exporting.value = false + } +} + function cnOf(subject: string) { const sub = subject || '' return sub.split('CN=').pop()?.split(',')[0]?.trim() || sub @@ -152,10 +214,6 @@ function pickProfile(e: Event) { } async function submit() { - if (!form.value.name.trim()) { - toast.error(t('admin.signProfiles.needName')) - return - } if (!certFile.value) { toast.error(t('admin.signProfiles.needCert')) return @@ -168,7 +226,6 @@ async function submit() { try { const fd = new FormData() fd.append('platform', form.value.platform) - fd.append('name', form.value.name.trim()) fd.append('password', form.value.password) fd.append('cert', certFile.value) if (crossFile.value) @@ -188,7 +245,6 @@ async function submit() { else { toast.success(t('admin.signProfiles.uploaded')) } - form.value.name = '' form.value.password = '' certFile.value = null profileFile.value = null @@ -283,13 +339,6 @@ onMounted(load) -
- {{ t('admin.signProfiles.name') }} - -
@@ -394,6 +443,10 @@ onMounted(load)
+ + {{ selected.length === identities.length && identities.length ? t('admin.signProfiles.unselectAll') : t('admin.signProfiles.selectAll') }} + + {{ t('admin.signProfiles.selectedCount', { n: selected.length }) }} {{ checking ? t('admin.signProfiles.checking') : t('admin.signProfiles.checkAll') }} @@ -403,10 +456,31 @@ onMounted(load)
+ +
+ {{ t('admin.signProfiles.exportTitle') }} + + + + + {{ exporting ? t('admin.signProfiles.exporting') : t('admin.signProfiles.exportSelected') }} + + {{ t('admin.signProfiles.exportHint') }} +
+
+ @@ -434,7 +508,10 @@ onMounted(load) - + + @@ -465,7 +542,7 @@ onMounted(load) - diff --git a/frontend/src/plugins/i18n/en.json b/frontend/src/plugins/i18n/en.json index f6c1807..f5f68a0 100644 --- a/frontend/src/plugins/i18n/en.json +++ b/frontend/src/plugins/i18n/en.json @@ -2720,7 +2720,19 @@ "checkProgress": "{done}/{total} checked", "revokeGood": "OK", "revokeBad": "Revoked", - "revokeUnknown": "Unavailable" + "revokeUnknown": "Unavailable", + "selectAll": "Select all", + "unselectAll": "Clear", + "selectedCount": "{n} selected", + "exportTitle": "Bulk export", + "exportPwd": "Export password (required)", + "exportSkipRevoked": "Skip revoked/blacklisted", + "exportSelected": "Export selected as zip", + "exporting": "Exporting…", + "exportDone": "Exported {n} certificates", + "exportHint": "Each pfx holds one identity; filenames carry index + CN", + "exportPwdHint": "Password must be at least 4 characters", + "nothingToExport": "Nothing to export" } }, "auth": { diff --git a/frontend/src/plugins/i18n/zh.json b/frontend/src/plugins/i18n/zh.json index 6374b4e..d280cf4 100644 --- a/frontend/src/plugins/i18n/zh.json +++ b/frontend/src/plugins/i18n/zh.json @@ -2739,7 +2739,19 @@ "checkProgress": "已检测 {done}/{total}", "revokeGood": "正常", "revokeBad": "已吊销", - "revokeUnknown": "查不到" + "revokeUnknown": "查不到", + "selectAll": "全选", + "unselectAll": "取消全选", + "selectedCount": "已选 {n} 套", + "exportTitle": "批量导出", + "exportPwd": "设置导出密码(必填)", + "exportSkipRevoked": "跳过已吊销/已拉黑", + "exportSelected": "导出选中为 zip", + "exporting": "导出中…", + "exportDone": "已导出 {n} 套证书", + "exportHint": "每个 pfx 只含一套私钥+证书,文件名带序号和 CN", + "exportPwdHint": "导出密码至少 4 位(pfx 必须有口令)", + "nothingToExport": "没有可导出的身份" } }, "auth": {
+ + {{ t('admin.signProfiles.colIndex') }}
+ + {{ it.index }}
+ {{ t('admin.signProfiles.checking') }}