Skip to content

Instantly share code, notes, and snippets.

@coreyasmith
Last active January 29, 2023 13:31
Show Gist options
  • Save coreyasmith/693126c6949af3a63157de378657f23c to your computer and use it in GitHub Desktop.
Save coreyasmith/693126c6949af3a63157de378657f23c to your computer and use it in GitHub Desktop.
Create a trusted, self-signed certificate with PowerShell. Inspiration comes from Dominick Baier's (@leastprivilege) "Web API v2 Security" course on Pluralsight: https://www.pluralsight.com/courses/webapi-v2-security.
Param(
[Parameter(Mandatory=$true)]
[string[]]$DnsName,
[DateTime]$CertExpirationDate = (Get-Date).AddYears(5),
[string]$PersonalCertStoreLocation = "Cert:\LocalMachine\My",
[string]$HashAlgorithm = "SHA512",
[string]$RootCertSubject = "CN=DevRoot",
[string]$RootCertStoreLocation = "Cert:\LocalMachine\Root",
[DateTime]$RootCertExpirationDate = (Get-Date).AddYears(20)
)
Function New-SelfSignedRootCertificate {
Param(
[Parameter(Mandatory=$true)]
[string]$RootCertSubject,
[Parameter(Mandatory=$true)]
[string]$RootCertStoreLocation
)
$rootCertificate = New-SelfSignedCertificate -Subject $RootCertSubject `
-CertStoreLocation $PersonalCertStoreLocation `
-HashAlgorithm $HashAlgorithm `
-KeyUsage CertSign,CRLSign `
-KeyExportPolicy Exportable `
-TextExtension @("2.5.29.19={text}ca=true") `
-NotAfter $RootCertExpirationDate
Copy-Certificate -Certificate $rootCertificate `
-DestinationCertStore $RootCertStoreLocation
}
Function Copy-Certificate {
Param(
[Parameter(Mandatory=$true)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(Mandatory=$true)]
[string]$DestinationCertStore
)
$destinationStore = Get-Item $DestinationCertStore
$destinationStore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$destinationStore.Add($Certificate)
$destinationStore.Close()
Get-ChildItem -Path $DestinationCertStore |
Where-Object { $_.Thumbprint -eq $Certificate.Thumbprint } |
Select-Object -First 1
}
$rootCertificate = Get-ChildItem -Path $RootCertStoreLocation |
Where-Object { $_.Subject -eq $RootCertSubject } |
Select-Object -First 1
if (!$rootCertificate) {
Write-Host "Root certificate not found. Generating new one."
$rootCertificate = New-SelfSignedRootCertificate -RootCertSubject $RootCertSubject `
-RootCertStoreLocation $RootCertStoreLocation
}
New-SelfSignedCertificate -DnsName $DnsName `
-CertStoreLocation $PersonalCertStoreLocation `
-HashAlgorithm $HashAlgorithm `
-NotAfter $CertExpirationDate `
-Signer $rootCertificate
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment