powershell - 在 Powershell 中使用 Import-PfxCertificate 命令安装证书 pfx 文件时找不到私钥
问题描述
我正在使用任务计划程序自动安装证书。证书包含 pfx 文件中的私钥。当我双击安装 pfx 文件时,它适用于我的 dot net 项目。但是当我使用 powershell 命令安装它时:
$password = ConvertTo-SecureString "apass" -AsPlainText -Force
Import-PfxCertificate –FilePath C:\cert\certMob2019.pfx cert:\localMachine\Root -Password $password
证书成功安装在正确的商店中。但是我的 dot net 项目产生了这个错误:
System.Security.Cryptography.CryptographicException: 'Object contains only the public half of a key pair. A private key must also be provided.'
解决方案
使用 Import-PfxCertificate 安装时,它不会在容器中导入私钥。替代方法是使用 C# 脚本安装:
X509Certificate2 cert = new X509Certificate2(pfxfilewithlocation.pfx, Password, X509KeyStorageFlags.PersistKeySet);
using (X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine))
{
store.Open(OpenFlags.ReadWrite);
try
{
store.Add(cert);
int indexInStore = store.Certificates.IndexOf(cert);
cert = store.Certificates[indexInStore];
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
X509KeyStorageFlags.PersistKeySet 使私钥持久化并访问所有应用程序
推荐阅读
- java - Javafx ListView 动态更新
- c# - 引用另一个项目,但不能在我当前的项目中使用它
- c# - Selenium click 方法正在执行然后超时
- mysql - 防止脚本在 docker 容器中退出
- java-8 - 如何解决 Java 8 函数式编程中的不兼容类型错误
- java - 改造不包含参数
- javascript - 在特定的执行上下文(iframe)上运行 javascript
- python - 使用 tensorboard Python Tensorflow 显示模型的实时训练
- firefox - 你可以使用 Rust 编写 Firefox 附加组件/扩展吗?
- python - 重新采样总和保持每天熊猫最后一次观察的指数