user584018
user584018

Reputation: 11304

how to install the certificate in certificate store without private key?

I have below 2 methods,

GetCaCertificate method reads the PFX certificate with has private key included.

AddCertToStore method add the certificate to the certificate store, here I want to add the certificate in the certificate store with-out Private key, how we can avoid it?

enter image description here

var rootCaCert = GetCaCertificate(@"C:\cert\ca-cert.pfx", "Password@123");

AddCertToStore(rootCaCert, StoreName.Root, StoreLocation.LocalMachine);

private static X509Certificate2 GetCaCertificate(string certPath, string password)
    {
        return new X509Certificate2(File.ReadAllBytes(certPath), password:password);
    }

public static bool AddCertToStore(X509Certificate2 cert, StoreName storeName, StoreLocation storeLocation)
    {
        bool value;

        try
        {
            using var store = new X509Store(storeName, storeLocation);
            store.Open(OpenFlags.ReadWrite);
            store.Add(cert);
            store.Close();

            value = true;
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception);
            value = false;
        }

        return value;
    }

Upvotes: 0

Views: 1404

Answers (1)

Crypt32
Crypt32

Reputation: 13924

Get a copy of public part of the certificate and add it to the store. That is, replace this line:

store.Add(cert);

with this:

store.Add(new X509Certificate2(cert.RawData));

in this case, you will install only public part of the certificate without associating it with private key.

Upvotes: 2

Related Questions