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
1 2 3 4 5 6 7 | $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
1 2 3 4 5 6 7 8 | $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
Hi, Michael Albert.
Thank you for this example,
It’s perfection!
Amigo… tarde horas y horas buscando en muchos foros, páginas y tu respuesta fue la correcta.
Complemento tu publicación para más colegas.. soy de méxico y necesitaba convertir un archivo .cer a .pem.. para la factura electrónica.
El archivo .cer ya lo tenia en byte[]
var certificate = new X509Certificate2(pCertificado);
var oCert = certificate.Export(X509ContentType.Cert);
certificate = new X509Certificate2(oCert);
var oPem = new StringBuilder();
oPem.AppendLine(“—–BEGIN CERTIFICATE—–“);
oPem.AppendLine(Convert.ToBase64String(certificate.RawData, Base64FormattingOptions.InsertLineBreaks));
oPem.AppendLine(“—–END CERTIFICATE—–“);
Hi Raul,
Thx, I don’t speak mexican
but could “follow” your comment.
Michael
Thank you for this easy solution.
Really appreciate it.