首页 > 解决方案 > 在 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.'

标签: powershellx509certificate

解决方案


使用 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 使私钥持久化并访问所有应用程序


推荐阅读