PFX to Pem Converter via Powershell not Openssl

Had an issue getting Legacy OpenSSL working on my PC

param(
    [Parameter(Mandatory = $true)]
    [string]$PfxPath,

    [Parameter(Mandatory = $true)]
    [string]$PfxPassword,

    [string]$CertOut = ".\cert.pem",
    [string]$KeyOut  = ".\key.pem"
)

$securePassword = ConvertTo-SecureString $PfxPassword -AsPlainText -Force

$flags = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable `
    -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet

$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new(
    $PfxPath,
    $securePassword,
    $flags
)

if (-not $cert.RawData) {
    throw "Failed to load certificate from PFX."
}

$certPem = @(
    "-----BEGIN CERTIFICATE-----"
    [Convert]::ToBase64String($cert.RawData, [Base64FormattingOptions]::InsertLineBreaks)
    "-----END CERTIFICATE-----"
) -join "`n"

Set-Content -Path $CertOut -Value $certPem

$rsa = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert)

if ($rsa) {
    $keyBytes = $rsa.ExportPkcs8PrivateKey()
    $keyPem = @(
        "-----BEGIN PRIVATE KEY-----"
        [Convert]::ToBase64String($keyBytes, [Base64FormattingOptions]::InsertLineBreaks)
        "-----END PRIVATE KEY-----"
    ) -join "`n"
    Set-Content -Path $KeyOut -Value $keyPem
    Write-Host "Wrote $CertOut and $KeyOut (RSA key)"
    exit 0
}

$ecdsa = [System.Security.Cryptography.X509Certificates.ECDsaCertificateExtensions]::GetECDsaPrivateKey($cert)

if ($ecdsa) {
    $keyBytes = $ecdsa.ExportPkcs8PrivateKey()
    $keyPem = @(
        "-----BEGIN PRIVATE KEY-----"
        [Convert]::ToBase64String($keyBytes, [Base64FormattingOptions]::InsertLineBreaks)
        "-----END PRIVATE KEY-----"
    ) -join "`n"
    Set-Content -Path $KeyOut -Value $keyPem
    Write-Host "Wrote $CertOut and $KeyOut (ECDSA key)"
    exit 0
}

throw "No exportable RSA or ECDSA private key found in the PFX."
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...