Last active
April 30, 2025 08:00
-
-
Save zjorz/8f67712d259c440140e9d254322286c0 to your computer and use it in GitHub Desktop.
Code To Generate Self-Signed Certificate That Can be Used For Multiple Purposes, Like Authenticating Against Application Registration In Entra ID, Token Signing Certificate or Token Encryption Certificate In Entra ID/ADFS/Whatever And Probably More Scenarios
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# To generate and export the certificate, local administrator rights in an elevated PowerShell window are required! | |
$certPurpose = "<CERTIFICATE PURPOSE>" # "Authentication", "Token Signing", "Token Encryption" # <= CONFIGURE THIS!!!!! | |
$svcDisplayName = "<SERVICE DISPLAY NAME AND/OR FQDN>" # <= CONFIGURE THIS!!!!! | |
$keyLength = 4096 # 4096 | 2048 # <= CONFIGURE THIS!!!!! | |
$daysBeforeToday = 0 # <= CONFIGURE THIS!!!!! (Positive Number For AFTER Today, Negative Number For Before Today!) | |
$daysAfterToday = 397 # 13 Months (Best Practice According To DigiCert) # <= CONFIGURE THIS!!!!! | |
$selfSignedCert = Invoke-Command -ArgumentList $certPurpose,$svcDisplayName,$keyLength,$daysBeforeToday,$daysAfterToday -ScriptBlock { | |
Param ( | |
$certPurpose, | |
$svcDisplayName, | |
$keyLength, | |
$daysBeforeToday, | |
$daysAfterToday | |
) | |
Clear-Host | |
Write-Host "" | |
Write-Host "###############################################################################" -Foregroundcolor Yellow | |
Write-Host "### Generate-Self-Signed-Certificate ###" -Foregroundcolor Yellow | |
Write-Host "###############################################################################" -Foregroundcolor Yellow | |
$date = Get-Date | |
$dateTime = Get-Date $date -Format "yyyy-MM-dd_HH.mm.ss" | |
$dateTimeShort = Get-Date $date -Format "yyyy-MM-dd" | |
$friendlyName = "$svcDisplayName $certPurpose Cert ($dateTimeShort)" | |
$description = "$svcDisplayName $certPurpose Cert ($dateTimeShort)" | |
$subjectName = "CN=$($certPurpose.Replace(" ","-")).$($svcDisplayName.Replace(" ","-"))" | |
$storeLocation = "Cert:\LocalMachine\My" | |
$certType = "Custom" | |
# https://learn.microsoft.com/en-us/windows/win32/seccertenroll/cryptoapi-cryptographic-service-providers | |
# https://www.pkisolutions.com/understanding-microsoft-crypto-providers/ | |
# https://www.gradenegger.eu/en/basics-cryptographic-service-provider-csp-and-key-storage-provider-ksp/ | |
$providerName = "Microsoft RSA Schannel Cryptographic Provider" | |
$signatureAlgorithm = "SHA256" | |
$algorithmName = "RSA" | |
$keyUsage = @("None") | |
$keyType = "KeyExchange" | |
$keyExportPolicy = "ExportableEncrypted" #(default) / "NonExportable" / "Exportable" | |
$dateTimeNotBefore = (Get-Date).AddDays($daysBeforeToday) | |
$dateTimeNotAfter = (Get-Date).AddDays($daysAfterToday) | |
$certsFolder = "C:\TEMP\CERT" | |
If (!(Test-Path $certsFolder)) { | |
[void](New-Item $certsFolder -ItemType Directory) | |
} | |
$cerFilePath = $($certsFolder + "\" + $dateTime + "_" + $($subjectName.Replace(":","_").Replace("/","_").Replace("\","_").SubString($subjectName.IndexOf("=") + 1)) + ".cer") | |
$pfxFilePath = $($certsFolder + "\" + $dateTime + "_" + $($subjectName.Replace(":","_").Replace("/","_").Replace("\","_").SubString($subjectName.IndexOf("=") + 1)) + ".pfx") | |
Write-Host "" | |
Write-Host " +++ $certPurpose Certificate For $svcDisplayName +++" -ForegroundColor Cyan | |
Write-Host "Certificate Friendly Name.........: $friendlyName" -ForegroundColor Magenta | |
Write-Host "Certificate Description...........: $description" -ForegroundColor Magenta | |
Write-Host "Certificate Subject Name..........: $subjectName" -ForegroundColor Magenta | |
Write-Host "Certificate Store Location........: $storeLocation" -ForegroundColor Magenta | |
Write-Host "Certificate Not Before (Approx.)..: $(Get-Date $dateTimeNotBefore -Format "yyyy-MM-dd HH:mm.ss") (Format: yyyy-MM-dd HH:mm:ss)" -ForegroundColor Magenta | |
Write-Host "Certificate Not After (Approx.)...: $(Get-Date $dateTimeNotAfter -Format "yyyy-MM-dd HH:mm.ss") (Format: yyyy-MM-dd HH:mm:ss)" -ForegroundColor Magenta | |
Write-Host "CER File Path.....................: $cerFilePath" -ForegroundColor Magenta | |
Write-Host "PFX File Path.....................: $pfxFilePath" -ForegroundColor Magenta | |
Write-Host "" | |
$pfxFileSecurePassword = Read-Host -Prompt "Please Provide A Password For The PFX File For The $certPurpose Certificate For '$svcDisplayName'" -AsSecureString | |
Write-Host "" | |
$selfSignedCert = New-SelfSignedCertificate -Type $certType -FriendlyName $friendlyName -KeyFriendlyName $friendlyName -KeyDescription $description -Subject $subjectName -CertStoreLocation $storeLocation -Provider $providerName -HashAlgorithm $signatureAlgorithm -KeyAlgorithm $algorithmName -KeyLength $keyLength -KeySpec $keyType -KeyUsage $keyUsage -NotBefore $dateTimeNotBefore -NotAfter $dateTimeNotAfter -KeyExportPolicy $keyExportPolicy | |
[void](Export-Certificate -Cert $selfSignedCert -FilePath $cerFilePath) | |
[void](Export-PfxCertificate -Cert $selfSignedCert -FilePath $pfxFilePath -Password $pfxFileSecurePassword) | |
Write-Host "" | |
Write-Host "Certificate NotBefore.............: $($selfSignedCert.NotBefore)" -ForegroundColor Magenta | |
Write-Host "Certificate NotAfter..............: $($selfSignedCert.NotAfter)" -ForegroundColor Magenta | |
Write-Host "Certificate SerialNumber..........: $($selfSignedCert.SerialNumber)" -ForegroundColor Magenta | |
Write-Host "Certificate Thumbprint............: $($selfSignedCert.Thumbprint)" -ForegroundColor Magenta | |
Write-Host "" | |
<# | |
This requires OPENSSL which can be downloaded from https://slproweb.com/products/Win32OpenSSL.html | |
To Convert PFX To PEM Format With Both CERT And KEY (With Password!) | |
OPENSSL.EXE pkcs12 -in "<FILE PATH>.pfx" -out "<FILE PATH>_cert-and-key-with-pwd.pem" -nodes | |
To Convert PFX To PEM Format With CERT Only | |
OPENSSL.EXE pkcs12 -in "<FILE PATH>.pfx" -clcerts -nokeys -out "<FILE PATH>_cert.pem" | |
To Convert PFX To PEM Format With KEY Only (With Password!) | |
OPENSSL.EXE pkcs12 -in "<FILE PATH>.pfx" -nocerts -out "<FILE PATH>_key-with-pwd.pem" | |
To Convert PFX To PEM Format With KEY Only (Passwordless!) | |
OPENSSL.EXE rsa -check -in "<FILE PATH>.pfx" -out "<FILE PATH>_key-with-no-pwd.pem" | |
#> | |
Return $selfSignedCert | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment