#Requires -Version 5.1 <# 生成自签名代码签名证书(仅用于本机与受控机器,不能消除别人的「未知发布者」提示)。 产物: certs\ZeroOrigin-CodeSign.cer 公钥证书,可提交仓库,供其他机器导入信任 %APPDATA%\ZerOriginTool\codesign\*.pfx 含私钥的备份(绝不进仓库),重装系统后用它恢复 %APPDATA%\ZerOriginTool\codesign\password.txt pfx 密码 用法:powershell -NoProfile -ExecutionPolicy Bypass -File scripts\codesign\new-cert.ps1 [-Force] #> [CmdletBinding()] param( [string]$Subject = 'CN=ZeroOrigin ToolBox, O=ZeroOrigin, C=CN', [int]$Years = 10, [switch]$Force ) $ErrorActionPreference = 'Stop' $root = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) # 仓库根 $cerDir = Join-Path $root 'certs' $backupDir = Join-Path $env:APPDATA 'ZerOriginTool\codesign' New-Item -ItemType Directory -Force -Path $cerDir, $backupDir | Out-Null $existing = Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert | Where-Object { $_.Subject -eq $Subject -and $_.HasPrivateKey } if ($existing -and -not $Force) { "已存在同名证书:$($existing[0].Thumbprint)($($existing[0].NotAfter.ToString('yyyy-MM-dd')) 到期);要重建请加 -Force" exit 0 } $cert = New-SelfSignedCertificate ` -Type CodeSigningCert ` -Subject $Subject ` -KeyUsage DigitalSignature ` -KeyAlgorithm RSA ` -KeyLength 3072 ` -HashAlgorithm SHA256 ` -CertStoreLocation Cert:\CurrentUser\My ` -NotAfter (Get-Date).AddYears($Years) $cerPath = Join-Path $cerDir 'ZeroOrigin-CodeSign.cer' Export-Certificate -Cert $cert -FilePath $cerPath -Force | Out-Null $password = -join ((48..57) + (65..90) + (97..122) | Get-Random -Count 24 | ForEach-Object { [char]$_ }) $secure = ConvertTo-SecureString -String $password -AsPlainText -Force $pfxPath = Join-Path $backupDir 'ZeroOrigin-CodeSign.pfx' Export-PfxCertificate -Cert $cert -FilePath $pfxPath -Password $secure | Out-Null Set-Content -Path (Join-Path $backupDir 'password.txt') -Value $password -Encoding ASCII "证书已生成" " 主题 : $($cert.Subject)" " 指纹 : $($cert.Thumbprint)" " 到期 : $($cert.NotAfter.ToString('yyyy-MM-dd'))" " 公钥证书 : $cerPath(可提交仓库,供其他机器导入)" " pfx 备份 : $pfxPath(含私钥,绝不进仓库)" " pfx 密码 : $password(同目录 password.txt 也有)"