Skip to main content

Automating the creation of a self-signed certificate in IIS

In order to use HTTPS (and everyone should use encryption) you need to use an SSL certificate. Usually, that means creating a Certificate Signing Request (CSR) and sending it to a public Certificate Authority (CA) to get a recognized certificate over the Internet. But if you have to host an internal web site, you may not need a public certificate. A good example is if you have a number of instances providing a web application, living behind a load balancer. The typical deployment methodology would be to have a single public SSL certificate that terminates at the load balancer, but you still want the traffic between the load balancer and the instances to be encrypted.

Here I will show you how to easily automate the creation of self-signed certificate for Windows instances using PowerShell. If you were to deploy it manually, you can use the IIS management console to do it, but in a modern deployment, you should automate the process. The first part is to create the actual certificate:

Import-Module WebAdministration
Set-Location IIS:\SslBindings
New-WebBinding -Name "Default Web Site" -IP "*" -Port 443 -Protocol https
$c = New-SelfSignedCertificate -DnsName "hostname" -CertStoreLocation cert:\LocalMachine\My
$c | New-Item!443

Here, replace hostname with the FQDN of the instance. This also assumes that you only have one web site called Default Web Site. After this runs, you will have a self-signed certificate in the $c variable. Then, you can simply add it to your machine’s root store:

$rootStore = New-Object System.Security.Cryptography.X509Certificates.X509Store "root", "LocalMachine"

And that’s it.