在Powershell中使用Import-PfxCertificate命令安装证书pfx文件时找不到私钥

时间:2019-12-18 12:19:36

标签: powershell x509certificate

我正在使用任务计划程序自动安装证书。该证书在pfx文件中包含私钥。当我双击安装pfx文件时,它可以很好地与我的dot net项目一起使用。但是,当我使用powershell命令安装它时:

$password =  ConvertTo-SecureString "apass" -AsPlainText -Force

Import-PfxCertificate –FilePath C:\cert\certMob2019.pfx cert:\localMachine\Root -Password $password

证书已正确安装在正确的存储中。但是我的点网项目会产生此错误:

System.Security.Cryptography.CryptographicException: 'Object contains only the public half of a key pair. A private key must also be provided.'

2 个答案:

答案 0 :(得分:0)

您必须在个人存储中而不是在根存储中安装PFX:cert:\localMachine\my

答案 1 :(得分:0)

使用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可以保留私钥并访问所有应用程序