文章

Windows脚本添加数字签名

Windows脚本添加数字签名

在 Windows 系统里,你可以借助 PowerShell 或者 SignTool 工具来为脚本添加数字签名。下面为你详细介绍操作步骤:

一、运用 PowerShell 签名

PowerShell 能够直接调用证书存储区中的证书来完成签名工作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
\# 1. 找出可用的代码签名证书


Get-ChildItem -Path cert:\CurrentUser\My -CodeSigningCert


\# 2. 对脚本进行签名(以test.ps1为例)


\$cert = Get-ChildItem -Path cert:\CurrentUser\My -CodeSigningCert | Select-Object -First 1


Set-AuthenticodeSignature -FilePath "C:\scripts\test.ps1" -Certificate \$cert


\# 3. 验证签名


Get-AuthenticodeSignature -FilePath "C:\scripts\test.ps1"

二、使用 SignTool 工具签名(需要安装 Windows SDK)

SignTool 是 Windows SDK 中的专业签名工具,支持使用 PFX 证书文件进行签名。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
\# 1. 对脚本签名(假设已将SignTool添加到环境变量)


signtool sign /f "C:\certificates\mycert.pfx" /p "证书密码" /t "http://timestamp.digicert.com" "C:\scripts\test.ps1"


\# 2. 详细签名(包含更多信息)


signtool sign /f "C:\certificates\mycert.pfx" /p "证书密码" /d "脚本描述" /du "https://example.com" /tr "http://timestamp.digicert.com" /td sha256 /fd sha256 "C:\scripts\test.ps1"


\# 3. 验证签名


signtool verify /pa "C:\scripts\test.ps1"

三、自签名证书的创建与使用

要是你没有正式的代码签名证书,能够创建一个自签名证书(不过这种证书仅适用于测试环境)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
\# 1. 创建自签名证书


\$cert = New-SelfSignedCertificate -Type CodeSigningCert -Subject "CN=MyCompany" -CertStoreLocation "Cert:\CurrentUser\My"


\# 2. 导出证书(可选操作)


Export-PfxCertificate -Cert \$cert -FilePath "C:\certificates\selfsigned.pfx" -Password (ConvertTo-SecureString -String "密码" -Force -AsPlainText)


\# 3. 使用自签名证书签名


Set-AuthenticodeSignature -FilePath "C:\scripts\test.ps1" -Certificate \$cert

四、注意要点

  1. 证书来源
  • 生产环境要使用由受信任的 CA(如 DigiCert、GlobalSign)颁发的代码签名证书。

  • 测试环境可以使用自签名证书,但客户端需要手动导入该证书。

  1. 时间戳服务器
  • 添加时间戳(/t/tr 参数)能保证签名在证书过期后依然有效。

  • 推荐使用知名的时间戳服务器,例如 DigiCert 的 http://timestamp.digicert.com

  1. 脚本执行策略
  • 签名后的脚本还得符合 PowerShell 的执行策略(像 RemoteSigned、AllSigned)。

  • 可以通过以下命令查看执行策略:Get-ExecutionPolicy

  • 若要修改执行策略,可使用:Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

通过上述方法,你就能够为 Windows 脚本添加数字签名,从而增强脚本的安全性和可信度。

(注:文档部分内容可能由 AI 生成)

本文由作者按照 CC BY 4.0 进行授权