无法使用 Windows signtool 进行代码签名

Unable to code sign with Windows signtool

我试图通过创建自己的自签名证书并成功签署文件来了解 Windows 上可执行文件的代码签名。 signtool 抛出错误并表示 "No certificates were found that met all the given criteria."

我做错了什么?

这是我所做的:

按照 MS 和其他博客的一些说明,我创建了一个自签名证书,如下所示:

New-SelfSignedCertificate -certstorelocation Cert:\LocalMachine\my -dnsname cameronnokes.com

$pwd = ConvertTo-SecureString -String "password" -Force -AsPlainText

Export-PfxCertificate -cert Cert:\LocalMachine\my\C7A94086D80A42151551A9FCCEACBC0B4A9ABA1A -FilePath 'C:\Users\Cameron Nokes\selfcert.pfx' -Password $pwd

Get-ChildItem -Recurse Cert:\LocalMachine\my

最后一个 Get-ChildItem 命令显示指纹和主题,看起来像我期望的那样。

现在,在 cmd 中,我 运行:

signtool.exe sign /f selfcert.pfx /p password /debug test.ps1


The following certificates were considered:
    Issued to: cameronnokes.com
    Issued by: cameronnokes.com
    Expires:   Sat Aug 05 12:37:28 2017
    SHA1 hash: C7A94086D80A42151551A9FCCEACBC0B4A9ABA1A

After EKU filter, 0 certs were left.
After expiry filter, 0 certs were left.
After Private Key filter, 0 certs were left.
SignTool Error: No certificates were found that met all the given criteria.

花点时间回忆一下 certreq 的怪癖,它默认存在,您可以使用它为您生成密钥。

制作这个 request.inf:

[NewRequest]
Subject = "CN=cameronnokes.com"
Exportable = TRUE
KeyLength = 2048
KeySpec = 1
KeyUsage = 0xA0
RequestType = Cert

[EnhancedKeyUsageExtension]
OID = 1.3.6.1.5.5.7.3.3 ; Code signing

然后运行这个命令:

certreq -new request.inf nothing.csr

然后您可以同时删除 request.inf 和 nothing.csr。此时你的个人商店中有一个自签名的代码签名证书。

$Certificate = Get-ChildItem cert:\CurrentUser\My |
    Where-Object { $_.EnhancedKeyUsageList.FriendlyName -eq 'Code Signing' -and $_.NotAfter -gt (Get-Date) } |
    Sort-Object NotAfter |
    Select-Object -Last 1

在选择证书的时候,你真的不想那么含糊,只是为了举例。

最后签一个ps1:

Set-AuthenticodeSignature test.ps1 -Certificate $Certificate

简单吧?