Question

I have the following code where SIGNED_FILENAME is a constant pointing to an existing pfx file that contains the private key.

X509Certificate2 cert = new X509Certificate2(SIGNED_FILENAME, PASSWORD, X509KeyStorageFlags.MachineKeySet);
RSACryptoServiceProvider certRsa = cert.PrivateKey as RSACryptoServiceProvider; 

When I use code to add permissions to the private key I find that they are set on the file specified in certRsa.CspKeyContainerInfo.UniqueKeyContainerName. When I view the certificate permissions in the Certificates mmc snap-in however there are no new permissions set.

When I set the keys manually via the Certificates mmc snap-in I find that the private key it sets the permissions on is different than the one I found in the UniqueContainerName property mentioned above.

TLDR: Each time I run those two lines of code the key container file changes.

Why would this be happening and how can I set the permissions on the same key that the Certificates mmc snap-in does?

Was it helpful?

Solution

Apparently because I was opening it from a file each time the key container was being re-generated (or something). Here is the code that works:

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
X509Certificate2 c = store.Certificates
    .Find(X509FindType.FindBySubjectName, SIGNED_SUBJECT, true) 
    .Cast<X509Certificate2>()
    .FirstOrDefault();
    store.Close();

RSACryptoServiceProvider rsa = c.PrivateKey as RSACryptoServiceProvider;
Console.WriteLine("Certificate thumbprint:" + c.Thumbprint);
Console.WriteLine("From machine key store?: " + rsa.CspKeyContainerInfo.MachineKeyStore);
Console.WriteLine("Key container name: " + rsa.CspKeyContainerInfo.KeyContainerName);
Console.WriteLine("Key unique container name: " + rsa.CspKeyContainerInfo.UniqueKeyContainerName);  

Previously when running the code snippet from my original post (where I open the certificate as a file) the key info that prints to the console would change each time. Running the modified code shows the same info each time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top