Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically import cert into IIS?

I have a .pem certificate for SSL, I want to distribute it with my web application in an MSI (has to run on clients' computers). I then need to import it (into some credentials store?) and tell my site bindings to use it. But how can I do this in code? I've discovered Microsoft.Web.Administration, but not sure where to go from there …

This is in IIS7 btw.

EDIT: The goal here is to have a web application that customers can run on their intranets. It mainly acts as an API for an iPhone app. (Maybe this isn't the best design but we're locked in now.) So the customer installs the MSI, and voila, they have a web service. Now there needs to be password authentication between the iPhone and the web service; the simplest way seemed to be to do it in https. So I made a self-signed cert.

I'm aware that redistributing a single cert is generally a bad idea, but we're just trying to defeat casual hackers here … this is going to be intranet only and for businesses only, it seems unlikely that anyone is going to be doing anything too crazy, and the API severely restricts the amount of Bad Things you are able to do to the database anyways.

So there we go, the goal is to have password authentication on an intranet web app, with one-click(ish) installation. :-D

like image 592
Dave Avatar asked Dec 21 '10 10:12

Dave


People also ask

How do I import and export SSL Certificates in IIS 10?

In the Add or Remove Snap-ins window, click OK. In the Console window, in the Console Root pane (left side), expand Certificates (Local Computer), right-click on the Web Hosting folder, and then click All Tasks > Import. In the Certificate Import Wizard, on the Welcome to the Certificate Import Wizard page, click Next.


1 Answers

The answer, dear readers, is this:

// Assume 'site' is already set to your site via something like 
// Site site = mgr.Sites.Add(siteName, directory, 443);

X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);

// Here, directory is my install dir, and (directory)\bin\certificate.pfx is where the cert file is.
// 1234 is the password to the certfile (exported from IIS)
X509Certificate2 certificate = new X509Certificate2(directory + @"\bin\certificate.pfx", "1234");

store.Add(certificate);

var binding = site.Bindings.Add("*:443:", certificate.GetCertHash(), store.Name);
binding.Protocol = "https";
store.Close();

Thanks to this random thread: http://forums.iis.net/t/1163325.aspx

like image 165
Dave Avatar answered Oct 06 '22 03:10

Dave