Menu

Virtual Geek

Tales from real IT system administrators world and non-production environment

PowerShell Create and Export Self-Signed RSA Certificates (PFX, CER, PEM)

This script helps creating SSL Self Signed Certificates and Private/Public key using PowerShell. PowerShell has inbuilt cmdlet command New-SelfSignedCertificate which is used to create proper SSL certificate which doesn't require third party applications such as OpenSSL or similar. There are multiple useful parameters you can use and provide while creating SSL certificate. This cert is created on windows in current user certificate store manager under personal certificates folder.

# Create a self-signed RSA certificate
$certInfo = @{
    Subject = "CN=vcloud-lab.com"
    FriendlyName = "vCloud Lab Self-Signed Certificate"
    KeyAlgorithm = "RSA"
    KeyLength = 2048
    NotAfter = (Get-Date).AddYears(1)
    CertStoreLocation = "Cert:\CurrentUser\My"
    DnsName = "vcloud-lab.com"
    KeyExportPolicy = 'Exportable'
    KeyUsage = @('DigitalSignature', 'KeyEncipherment')
}

$cert = New-SelfSignedCertificate @certInfo
Once certificate is generated you can see it as below screenshot. Just to note, it has SSL key inbuilt.

A self-signed RSA certificate generated via PowerShell, displayed in Windows Certificate Manager, showing its properties and issuer details. Image of a vcloud-lab.com self-signed certificate, created with PowerShell, within certmgr.msc, confirming its validity and exportability.

To view certificate detail use Get-ChildItem command in the cert store as shown below using certificate thumbprint. Same way you can delete this cert using Remove-Item coammnd.

# Get Information of newly created self signed certificate
Get-ChildItem -Path $certInfo.CertStoreLocation | Where-Object { $_.Thumbprint -eq $cert.Thumbprint } | Format-List

# Delete self signed certificate
Get-ChildItem -Path $certInfo.CertStoreLocation | Where-Object { $_.Thumbprint -eq $cert.Thumbprint } | Remove-Item -Force

Certificate details are shown as below.

PowerShell console output showing details of a self-signed certificate, including Subject, Issuer, Thumbprint, FriendlyName, NotBefore, NotAfter dates, and Extensions.

To export certificate to pfx with key use command Export-PfxCertificate command.

# Export to PFX (with private key)
$password = ConvertTo-SecureString -String "YourPassword" -Force -AsPlainText
Export-PfxCertificate `
    -Cert $cert `
    -FilePath "C:\Temp\certificate.pfx" `
    -Password $password

Alternatively if you want only cer or pem format, simply use Export-Certificate command with required parameters.

# Export public key (CER)
Export-Certificate `
    -Cert $cert `
    -FilePath "C:\Temp\certificate.cer"

Command used below are little advanced and you can create custom SSL certificate key, export it to public and private keys for future use.

# Generate RSA key pair (2048-bit)
$rsa = [System.Security.Cryptography.RSA]::Create(2048)

# Export the private key to a PEM string
$privateKeyPem = $rsa.ExportRSAPrivateKeyPem()

# Export the public key to a PEM string
$publicKeyPem = $rsa.ExportRSAPublicKeyPem()

# Define file paths for the keys
$privateKeyFilePath = "C:\Temp\private_key.pem"
$publicKeyFilePath = "C:\Temp\public_key.pem"

# Save the private key to a file
Set-Content -Path $privateKeyFilePath -Value $privateKeyPem

# Save the public key to a file
Set-Content -Path $publicKeyFilePath -Value $publicKeyPem

These command creates self signed certificate but using .NET object with PowerShell command, here you have more properties to configure for certificate. Just to note, it does not store certificate in store.

# Create certificate properties
$subject = [System.Security.Cryptography.X509Certificates.X500DistinguishedName]::new("CN=vcloud-lab.com")
$request = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new(
    $subject,
    $rsa,
    [System.Security.Cryptography.HashAlgorithmName]::SHA256,
    [System.Security.Cryptography.RSASignaturePadding]::Pkcs1
)

# Configure certificate validity (1 year)
$notBefore = [System.DateTimeOffset]::Now
$notAfter = $notBefore.AddYears(1)

# Generate self-signed certificate
$certificate = $request.CreateSelfSigned($notBefore, $notAfter)

Download this script bundle here or it is also available on github.com.

And using below .NET steps certificates can be downloaded.

# Export to PFX (with private key)
$pfxPassword = "YourPassword"
$pfxBytes = $certificate.Export(
    [System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx,
    $pfxPassword
)
[System.IO.File]::WriteAllBytes("C:Temp\certificate.pfx", $pfxBytes)

# Export public key (CER)
$cerBytes = $certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
[System.IO.File]::WriteAllBytes("C:\Temp\certificate.cer", $cerBytes)

Useful Articles
Find next available free drive letter using PowerShell
Copy Files with PowerShell Remoting WINRM Protocol
Powershell Find application window state minimized or maximized
How to Install and Use Microsoft PowerShell on Linux
Configure PowerShell remoting between Windows and Linux
Get-PSRepository WARNING Unable to find module repositories
Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send
Creating an internal PowerShell module repository
How to sign PowerShell ps1 scripts
PowerShell Convert MAC address to Link-local address IPv6
PowerShell fix repair The trust relationship between this workstation and the primary domain failed
Resovled issue with PowerShell - Trust relationship Rejoin computers in domain without restart
PowerShell Invoke-WebRequest The request was aborted Could not create SSL TLS secure channel
PowerShell Invoke-WebRequest The underlying connection was closed: Could not establish trust relationship for the SSL TLS secure channel.
Powershell Write-Eventlog The source name test does not exist on computer localhost
Powershell New-Object Retrieving the COM class factory for component with CLSID 80040154 Class not registered (Exception from HRESULT 0x80040154 (REGDB_E_CLASSNOTREG))

Go Back

Comment

Protected by Mathcha

Blog Search

Page Views

1 4 6 4 5 8 3 9

Archive

Follow me on Blogarama