Creating a self signed certificate for web development on IIS using powershell

We will need to run the following on Powershell with Administrator rights.

# Setup variables
$companyName = "contoso"
$certFilePath = "$PSScriptRoot\$companyName-wildcard.pfx"
$dnsName = "*.$"
$date = (Get-Date).ToString('MMM-yyyy')
$certFriendlyname = "$companyName-wildcard-$date"
$certExpiry = (Get-Date).AddYears(10)

# Removal existing certificates
gci Cert:\LocalMachine\Root | Where FriendlyName -Like "*$companyName*" | Remove-Item
gci Cert:\LocalMachine\My | Where FriendlyName -Like "*$companyName*" | Remove-Item

# Create self signed certificate and store thumbprint variable
$thumb = (New-SelfSignedCertificate -DnsName $dnsName -CertStoreLocation cert:\LocalMachine\My -FriendlyName $certFriendlyname -NotAfter $certExpiry).Thumbprint

# Export self signed certificate to local file system with mandatory password
$pwd = ConvertTo-SecureString -String "YourPassword" -Force -AsPlainText
Export-PfxCertificate -Cert cert:\LocalMachine\My\$thumb -FilePath $certFilePath -Password $pwd

# Adding the exported certificate into the Trusted Root Certificate Authorities store
Import-PfxCertificate -CertStoreLocation Cert:\LocalMachine\Root\ -FilePath $certFilePath -Password $pwd

# Rebinding existing ssl certificates in case Windows decides to remove third party certificates from Root
$bindings = Get-WebBinding | Where { $_.Protocol -eq "https" -and $_.bindingInformation -like "*$companyName*" }
$cert = gci Cert:\LocalMachine\MY | Where Subject -Like *$companyName* | select -First 1
foreach ($b in $bindings)
    $b.RebindSslCertificate($cert.GetCertHashString(), "My") | Out-Null

We can verify that all this has been done correctly by heading over to Windows > run > certlm.msc

  • Personal > Certificates and
  • Personal > Trusted Root Certification

And then check for the entry with "Issued By" as *

Then we will need to add an entry to override DNS by editing our host file on

Once all this is done, we can fire up IIS Manager (inetmgr) and add a binding to the website of our choice with the newly generated certificate.

Check on your favourite browser and make sure the location bar is green.

Reversal for everything above

Remove-Item Cert:\LocalMachine\My\$thumb
Remove-Item Cert:\LocalMachine\AuthRoot\$thumb
Remove-Item C:\contoso-wildcard.pfx

Important notes

It appears that sometimes these certificates get removed from the Root Store which results in errors like

This server could not prove that it is; its security certificate is not trusted by your computer's operating system. This may be caused by a misconfiguration or an attacker intercepting your connection.

It turns out that Windows has the ability to remove certs. Still need to figure out why and how we can stop this from happening.

These links could be related

comments powered by Disqus