Skip to content

Instantly share code, notes, and snippets.

@Yvand
Last active December 4, 2023 13:19
Show Gist options
  • Save Yvand/a818dd4113137cb85aa447155ff8726c to your computer and use it in GitHub Desktop.
Save Yvand/a818dd4113137cb85aa447155ff8726c to your computer and use it in GitHub Desktop.
Creates a self signed certificate, exports its public and private keys to the file system, and deletes it from the certificate store
# Variables to edit
$certificateSubjectName = "certificateSubjectName"
$certificatePath = "certificatePath"
$certificatePassword = "certificatePassword"
# Creates the self signed certificate
$certificate = New-SelfSignedCertificate -DnsName $certificateSubjectName -CertStoreLocation "cert:\CurrentUser\My" `
-NotAfter (Get-Date).AddYears(10) -FriendlyName $certificateSubjectName
if ($null -ne $certificate) {
# Exports the certificate's public key
Export-Certificate -Cert $certificate -FilePath (Join-Path -Path $certificatePath -ChildPath "$certificateSubjectName.cer") -Type CERT
# Exports the certificate's private key
$mypwd = ConvertTo-SecureString -String $certificatePassword -Force -AsPlainText
Get-ChildItem -Path "cert:\CurrentUser\my\$($certificate.Thumbprint)" | Export-PfxCertificate -FilePath (Join-Path -Path $certificatePath -ChildPath "$certificateSubjectName.pfx") -Password $mypwd
# Removes the certificate from the store
Remove-Item "cert:\CurrentUser\my\$($certificate.Thumbprint)"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment