这是@Sir Kill A Lot在他的回答中提供的相同方法,但已转换为 PowerShell 脚本 ( pfx2snk.ps1 )。
Param(
[Parameter(Mandatory=$True,Position=1)]
[string] $pfxFilePath,
[string] $pfxPassword
)
# The path to the snk file we're creating
[string] $snkFilePath = [IO.Path]::GetFileNameWithoutExtension($pfxFilePath) + ".snk";
# Read in the bytes of the pfx file
[byte[]] $pfxBytes = Get-Content $pfxFilePath -Encoding Byte;
# Get a cert object from the pfx bytes with the private key marked as exportable
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2(
$pfxBytes,
$pfxPassword,
[Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable);
# Export a CSP blob from the cert (which is the same format as an SNK file)
[byte[]] $snkBytes = ([Security.Cryptography.RSACryptoServiceProvider]$cert.PrivateKey).ExportCspBlob($true);
# Write the CSP blob/SNK bytes to the snk file
[IO.File]::WriteAllBytes($snkFilePath, $snkBytes);
只需运行提供 pfx 文件路径和密码的脚本,它就会在与 pfx 文件相同的目录中创建一个 snk 文件(除了扩展名之外具有相同的名称)。
powershell.exe -File pfx2snk.ps1 -pfxFilePath cert.pfx -pfxPassword "pfx password"
或者,如果您的 pfx 没有密码(可耻,可耻):
powershell.exe -File pfx2snk.ps1 cert.pfx
而且,如果您不幸在不允许执行 PowerShell 脚本的环境中工作(即仅交互式 PowerShell 会话),那么您可以从标准 cmd.exe 命令行(根据需要替换文件路径和 pfx 密码)。
powershell.exe -Command "[IO.File]::WriteAllBytes('SnkFilePath.snk', ([Security.Cryptography.RSACryptoServiceProvider](New-Object System.Security.Cryptography.X509Certificates.X509Certificate2((Get-Content 'PfxFilePath.pfx' -Encoding Byte), 'PfxPassword', [Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)).PrivateKey).ExportCspBlob($true));"
实际上,我使用该单行代码作为我的 Visual Studio 预构建过程的标准部分,以自动化使用来自我们的身份验证签名证书(pfx 文件)的相同密钥进行强名称签名的过程。这不是一个要求,但对我来说,它们应该是相同的似乎是有道理的,并且它助长了我的强迫症倾向。
(我使用 snk 文件而不是原始 pfx,因为我有使用 pfx 文件进行强名称签名的“错误”经验,@punkcoder在他的回答中提到)
而且,如果您有兴趣,我在 Visual Studio 中的后期构建过程中有类似以下内容的内容,以将身份验证签名添加到项目输出中(无论如何在“发布”项目配置中)。
powershell.exe -Command "Set-AuthenticodeSignature -FilePath '$(TargetPath)' -Certificate '$(SolutionDir)MyCert.pfx' -TimestampServer http://timestamp.verisign.com/scripts/timstamp.dll -HashAlgorithm sha256;"