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

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

我正在使用任务自动安装证书 scheduler.The 证书在 pfx 文件中包含私钥。当我双击安装 pfx 文件时,它在我的点网项目中工作正常。但是当我使用 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.'

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

在使用 Import-PfxCertificate 安装时,它不会导入私钥 containers.The 替代方法是使用 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 使私钥持久化并访问所有应用程序