Search code examples
ssliisssl-certificateiis-7.5iis-8

Where does IIS import cert to?


I am trying to replicate what IIS Import does. I have an application that needs to import the certificates programmatically but its not working because i seem to be missing a step. If i import the same certificate through IIS Import utility it works perfectly.

In code:

private X509Certificate2Collection x509 = new X509Certificate2Collection();
private X509Store IIS = new X509Store(StoreName.My, StoreLocation.LocalMachine);

x509.Import(path, password, X509KeyStorageFlags.Exportable);
var certificate = new X509Certificate2(path, password, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
IIS.Open(OpenFlags.ReadWrite);
IIS.Add(certificate);
IIS.Close();

netsh http add sslcert ipport=0.0.0.0:" + port.ToString() + " certhash=" + CertificateThumbprint + " appid={2d967d25-4edf-4962-9b6c-5b3c4d4de48d}";

The netsh binding FAILS with the error a specified logon session does not exist. it may already have been terminated

IF i first import the certificate through the IIS manager, THEN run the netsh command, this all works just fine so i must be missing something in my code that IIS is doing in the background..


Solution

  • Because you didn't set X509KeyStorageFlags.PersistKeySet as required, the certificate is in fact not imported to the store as you wished.

    Further explanation can be found in KB950090