创建了 PFX 证书但未启用加密

Ste*_*ric 1 powershell certificate

我通过以下方式使用 Visual Studio 开发人员命令提示符创建了 PFX 证书;

makecert -r -pe -n "CN=mycert" -sky exchange "mycert.cer" -sv "mycert.pvk"
pvk2pfx -pvk "mycert.pvk" -spc "mycert.cer" -pfx "mycert.pfx" -pi [password]
Run Code Online (Sandbox Code Playgroud)

然后我使用 PowerShell 来查询证书

$cert = Get-PfxCertificate [Location]
$cert.Verify()
# Returns 'False'
Run Code Online (Sandbox Code Playgroud)

如何获得此证书以用于加密?

更新

@root 建议使用Import-PfxCertificate命令。这是我运行它时发生的情况。

Import-PfxCertificate -FilePath [Path]
Import-PfxCertificate : The PFX file you are trying to import requires either a different password or membership in an Active Directory principal to which it is protected.
At line:1 char:1
+ Import-PfxCertificate -FilePath [...]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Import-PfxCertificate], Win32Exception
    + FullyQualifiedErrorId : System.ComponentModel.Win32Exception,Microsoft.CertificateServices.Commands.Im 
   portPfxCertificate
Run Code Online (Sandbox Code Playgroud)

进一步更新

@McDonald 提出了一种将密码传递给Import-PfxCertificate命令的安全方法。这是我尝试过的;

Import-PfxCertificate -FilePath [Path] -Password (Get-Credential).Password
$cert = dir cert:\localmachine\my | where { $_.Thumbprint -eq [Thumbprint] } | Select-Object
$cert.Verify()
Run Code Online (Sandbox Code Playgroud)

仍然返回false。还有什么线索吗?

Ben*_*n N 5

Verify方法检查证书是否可信。要确切了解验证失败的原因,我们需要构建链:

$cert = Get-PfxCertificate -FilePath .\mycert.pfx
$chain = New-Object System.Security.Cryptography.X509Certificates.X509Chain
$chain.Build($cert)
$chain.ChainStatus
Run Code Online (Sandbox Code Playgroud)

当我重复您的步骤并运行这些命令时,我的状态UntrustedRoot. 这意味着验证失败,因为证书不是由受信任的证书颁发机构签署的,考虑到我们对其进行自签名(打开-r开关makecert),这是有道理的。

要验证证书,请将其导入受信任的根证书颁发机构存储:

Import-PfxCertificate -CertStoreLocation Cert:\CurrentUser\Root -FilePath .\testcert.pfx -Password (Read-Host 'Password' -AsSecureString)
Run Code Online (Sandbox Code Playgroud)

输入 PFX 密码,接受大警告对话框,证书将被添加。然后验证通过。如果您更喜欢 GUI,certmgr.msc可以完成这项工作。


但是,您可以在计算机不信任证书的情况下使用 RSA 参数。假设数字 137 是发送给私钥持有者的秘密消息。我们可以使用公钥来加密我们的消息:

$public = Get-PfxCertificate .\mycert.cer
$public.PublicKey.Key.Encrypt(@(137), $false)
Run Code Online (Sandbox Code Playgroud)

然后以某种方式生成的加密大字节数组(称为$message)到达私钥持有者,后者恢复原始数字:

$private = Get-PfxCertificate .\mycert.pfx
$private.PrivateKey.Decrypt($message)
Run Code Online (Sandbox Code Playgroud)

通常更有趣/更高级的东西(见 MSDN)会用钥匙来完成。关键是,应用程序可以在不受机器信任的情况下使用证书。