In the last post we saw how we can extract certificate from a PKCS7 store. In this post we will see two different ways how we can register a certificate into local store using C#.
The first method that can be used to register a certificate into the store is using X509Store class.
The first command install the certificate in the local store:
The most important command, when you need to assign a private key to a certificate that don’t has a private key is the second one.
Good luck!
The first method that can be used to register a certificate into the store is using X509Store class.
X509Certificate2 cert = new X509Certificate2(...)
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
store.Close();
If you want to import the private key to the certificate you will need to need to specify to the certificate constructor the flag that say to the system “Please, persist the private key".
X509Certificate2 cert = new X509Certificate2 (
[path],
[password],
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
store.Close();
This solution will works in 99.9% cases, but I had the luck to discover that there are some certificates that don’t accept the import of private key using C# code. I didn’t understood why the private key is not imported, but it seems that there are cases when the private key is not persisted.
In this situations, the only solution that I found is to make a step backward and use command line commands. You will need to use two different commands.The first command install the certificate in the local store:
certutil -user -privatekey -addstore my [certificatePath]
The second command will “repair” the certificate, basically the private key is added to the certificate.
certutil -user -repairstore my "[certThumbprint]"
To be able to use the second command you will need to specify the thumbprint of the certificate. This can be obtain very easily from the store (X509Store). Each command like command can run from C# using “Process.Start(command,paramas);”.The most important command, when you need to assign a private key to a certificate that don’t has a private key is the second one.
Good luck!
Comments
Post a Comment