简体   繁体   English

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

[英]private key not found while certificate pfx file installed with Import-PfxCertificate command in powershell

I was automating installing a certificate with a task scheduler.The certificate contains private key in a pfx file.我正在使用任务调度程序自动安装证书。证书在 pfx 文件中包含私钥。 When i install the pfx file with double click it works fine with my dot net project.当我双击安装 pfx 文件时,它在我的 dot net 项目中工作正常。 But while i install it with powershell command :但是当我使用 powershell 命令安装它时:

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

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

the certificate install successfully in correct store.证书在正确的存储中成功安装。 But my dot net project generate this error:但是我的 dot net 项目产生了这个错误:

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

While installing with Import-PfxCertificate it dont import the private key in containers.The alternateway is installing with C# script:使用 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 make the private key persist and access to all applications X509KeyStorageFlags.PersistKeySet 使私钥持久化并访问所有应用程序

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM