feat(protect): 证书名直接用 CN,去掉自定义名称;支持批量带密码导出
Docker Build / Build and Push Docker Image (push) Successful in 59s
Docker Build / Deploy to Server (push) Successful in 3s

用户要求:
1) 不需要自定义名称,直接用证书名称(CN)显示;
2) 支持批量导出、导出时可设置密码。

改动:
- 上传不再要 name:解析出证书后 name 直接写成 CN(首个身份的 CN);
  列表去掉「名称」列,只留「证书名称(CN)」并放到第一列
- 新增 POST /dev/sign-profiles/:id/export:
  body {identities:[..] | all:true, password, skip_revoked, check_revoked}
  按套重打包成单身份 pfx(用用户指定口令,pkcs12.Modern,失败退 LegacyRC2),
  打 zip 返回;文件名 001_<CN>.pfx,另附 README.txt(口令 + signtool 用法)
  可选跳过已吊销/已拉黑的身份
- SplitPFX 拆出 SplitPFXWithPassword(导出时换口令,签名时沿用原口令)
- 前端身份对话框:勾选列 + 全选 + 「批量导出」工具条(密码输入 + 跳过已吊销),
  导出走 fetch 拿 blob 直接下载

实测(真实 79 套包):
- 上传后 name 自动 = 浙江恒歌网络科技有限公司(CN)
- 导出 all + 跳过已吊销 → zip 231KB、76 条目(75 套 pfx + README),
  X-Exported: 75,4 套被吊销的按预期跳过
- 用导出密码 exportpw888 取 001_浙江恒歌....pfx 签 .sys → Succeeded,
  签名写入正常(证明重打包的 pfx 可用)
- 浏览器点「导出选中为 zip」→ POST .../export 200(323ms)
This commit is contained in:
hermes
2026-11-22 14:36:55 +08:00
parent b42a40434f
commit e026dc1364
7 changed files with 344 additions and 33 deletions
+12 -2
View File
@@ -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{
+197
View File
@@ -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,内含 <序号>_<CN>.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
}
+10 -3
View File
@@ -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 指定用哪一套,签名那一刻才拆。
@@ -21,14 +21,7 @@ interface ColumnOptions {
export function getColumns(options: ColumnOptions, t: (key: string) => string): ColumnDef<SignProfile>[] {
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',
@@ -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<File | null>(null)
@@ -34,6 +34,10 @@ const identityProfile = ref<SignProfile | null>(null)
const identities = ref<any[]>([])
const identityLoading = ref(false)
const checking = ref(false)
const selected = ref<number[]>([])
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)
</UiSelectContent>
</UiSelect>
</div>
<div class="space-y-2">
<UiLabel>{{ t('admin.signProfiles.name') }}</UiLabel>
<UiInput
v-model="form.name"
:placeholder="t('admin.signProfiles.namePlaceholder')"
/>
</div>
</div>
<div class="grid gap-4 sm:grid-cols-2">
@@ -394,6 +443,10 @@ onMounted(load)
</UiDialogHeader>
<div class="flex flex-wrap items-center gap-2">
<UiButton size="sm" variant="outline" @click="toggleAll(selected.length !== identities.length)">
{{ selected.length === identities.length && identities.length ? t('admin.signProfiles.unselectAll') : t('admin.signProfiles.selectAll') }}
</UiButton>
<span class="text-xs text-muted-foreground">{{ t('admin.signProfiles.selectedCount', { n: selected.length }) }}</span>
<UiButton size="sm" :disabled="checking || identityLoading" @click="checkAll">
<Loader2 v-if="checking" class="mr-1.5 h-3.5 w-3.5 animate-spin" />
{{ checking ? t('admin.signProfiles.checking') : t('admin.signProfiles.checkAll') }}
@@ -403,10 +456,31 @@ onMounted(load)
</span>
</div>
<!-- 批量导出:带密码导出成 zip(每个 pfx 一套身份) -->
<div class="flex flex-wrap items-center gap-2 rounded-md border bg-muted/30 p-2">
<span class="text-xs font-medium">{{ t('admin.signProfiles.exportTitle') }}</span>
<UiInput v-model="exportPassword" type="password" class="h-8 w-44"
:placeholder="t('admin.signProfiles.exportPwd')" />
<label class="flex items-center gap-1 text-xs text-muted-foreground">
<input v-model="exportSkipRevoked" type="checkbox" class="h-3.5 w-3.5">
{{ t('admin.signProfiles.exportSkipRevoked') }}
</label>
<UiButton size="sm" :disabled="exporting || identityLoading" @click="exportSelected">
<Loader2 v-if="exporting" class="mr-1.5 h-3.5 w-3.5 animate-spin" />
{{ exporting ? t('admin.signProfiles.exporting') : t('admin.signProfiles.exportSelected') }}
</UiButton>
<span class="text-xs text-muted-foreground">{{ t('admin.signProfiles.exportHint') }}</span>
</div>
<div class="max-h-[60vh] overflow-auto rounded-md border">
<table class="w-full text-sm">
<thead class="sticky top-0 bg-muted/80 backdrop-blur">
<tr class="text-left text-xs text-muted-foreground">
<th class="w-8 px-2 py-2">
<input type="checkbox" class="h-3.5 w-3.5"
:checked="identities.length > 0 && selected.length === identities.length"
@change="toggleAll(($event.target as HTMLInputElement).checked)">
</th>
<th class="px-2 py-2">
{{ t('admin.signProfiles.colIndex') }}
</th>
@@ -434,7 +508,10 @@ onMounted(load)
</tr>
</thead>
<tbody>
<tr v-for="it in identities" :key="it.index" class="border-t">
<tr v-for="it in identities" :key="it.index" class="border-t" :class="{ 'bg-muted/30': selected.includes(it.index) }">
<td class="px-2 py-1.5">
<input v-model="selected" type="checkbox" :value="it.index" class="h-3.5 w-3.5">
</td>
<td class="px-2 py-1.5 font-mono text-xs text-muted-foreground">
{{ it.index }}
</td>
@@ -465,7 +542,7 @@ onMounted(load)
</td>
</tr>
<tr v-if="identityLoading">
<td colspan="8" class="px-2 py-6 text-center text-xs text-muted-foreground">
<td colspan="9" class="px-2 py-6 text-center text-xs text-muted-foreground">
{{ t('admin.signProfiles.checking') }}
</td>
</tr>
+13 -1
View File
@@ -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": {
+13 -1
View File
@@ -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": {