Powershell: Export/Convert a X509 Certificate to pem format

Hi,

powershell respectively the .NET framework does not offer a method to export a X509 certificate in PEM format. The pem format is a Base64 encoded view from the raw data with a header and a footer.

An example to export the machine certificate (with Thumbprint: 1C0381278083E3CB026E46A7FF09FC4B79543D) of an computer

$InsertLineBreaks=1
$oMachineCert=get-item Cert:\LocalMachine\My\1C0381278083E3CB026E46A7FF09FC4B79543D
$oPem=new-object System.Text.StringBuilder
$oPem.AppendLine("-----BEGIN CERTIFICATE-----")
$oPem.AppendLine([System.Convert]::ToBase64String($oMachineCert.RawData,$InsertLineBreaks))
$oPem.AppendLine("-----END CERTIFICATE-----")
$oPem.ToString() | out-file D:\Temp\my.pem

Or load a certificate from a file and convert it to pem format

$InsertLineBreaks=1
$sMyCert="D:\temp\myCert.der"
$oMyCert=New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($sMyCert)
$oPem=new-object System.Text.StringBuilder
$oPem.AppendLine("-----BEGIN CERTIFICATE-----")
$oPem.AppendLine([System.Convert]::ToBase64String($oMyCert.RawData,$InsertLineBreaks))
$oPem.AppendLine("-----END CERTIFICATE-----")
$oPem.ToString() | out-file D:\Temp\my.pem

Michael

Advertisment to support michlstechblog.info

One thought on “Powershell: Export/Convert a X509 Certificate to pem format”

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.