0

I was automating installing a certificate with a task scheduler.The certificate contains private key in a pfx file. When i install the pfx file with double click it works fine with my dot net project. But while i install it with powershell command :

$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:

System.Security.Cryptography.CryptographicException: 'Object contains only the public half of a key pair. A private key must also be provided.'
  • please check [link](https://stackoverflow.com/questions/40046916/how-to-grant-permission-to-user-on-certificate-private-key-using-powershell) and see if it helps. – hcm Dec 18 '19 at 12:39
  • it doesnt help because i dont know for what user it install pfx while installing with gui – Syed Mohammad Fahim Abrar Dec 18 '19 at 12:47

2 Answers2

1

While installing with Import-PfxCertificate it dont import the private key in containers.The alternateway is installing with C# script:

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

0

You must install the PFX in Personal store, not in Root store: cert:\localMachine\my

Crypt32
  • 12,850
  • 2
  • 41
  • 70