Skip to content

Instantly share code, notes, and snippets.

@kojoru
Created February 14, 2020 08:49
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kojoru/6fb96a3ebc16bf087c8452598558c3c5 to your computer and use it in GitHub Desktop.
This creates, installs and trusts a self-signed certificate for http.sys-based application
# Usage: Install-SeftSignedCertificate.ps1 -port 40443
[CmdletBinding(DefaultParameterSetName="port")]
param(
# Port which will be covered by a certificate
[Parameter(Mandatory=$true, ParameterSetName="Port")]
[Int32]$port,
# How many years the certificate will be valid for
[Parameter(ParameterSetName="CertificateValidityYears")]
[Int32]$years = 5,
# A GUID for associating a netsh ssl record with your app
[Parameter(ParameterSetName="ApplicationGuid")]
[guid]$appid = "5caff01d-10ad-7e57-c0de-decafc0ffee5"
)
$cert = New-SelfSignedCertificate -DnsName "localhost", "localhost" -CertStoreLocation "cert:\LocalMachine\My" -NotAfter (Get-Date).AddYears($years) -FriendlyName "Certificate for port $port. Created by a script."
$thumb = $cert.GetCertHashString()
netsh http delete sslcert ipport=0.0.0.0:$port # this will throw an error if no certificates are installed, that can be safely ignored
netsh http add sslcert ipport=0.0.0.0:$port certhash=$thumb appid="{$appid}"
$StoreScope = 'LocalMachine'
$StoreName = 'root'
$Store = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Store -ArgumentList $StoreName, $StoreScope
$Store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$Store.Add($cert)
$Store.Close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment