PowerShell – Convert DER Encoded Certificate file into a Base64 .cer

System Requirements:

  • Windows PowerShell

The Problem:

If you have a binary encoded .cer (certificate) file that you need to get into a Base64 format, you can either follow the advice and use OpenSSL to convert it or you can import it into the Windows Certificate Store and re-export it.

If you want to do it automatically, without having to download and install anything else, neither option is particularly appealing.

The Fix

You can use the following function to convert the binary encoded file into a Base64 ASCII encoded file

function Convert-CertificateBinaryToBase64 {
  param( [string]$SourceFile, [string]$DestinationFile )
  $cert = get-content "$SourceFile" -Encoding Byte
  $content = @(
    '-----BEGIN CERTIFICATE-----'
    [System.Convert]::ToBase64String($cert, 'InsertLineBreaks')
    '-----END CERTIFICATE-----'
  $content | Out-File -FilePath "$DestinationFile" -Encoding ASCII

Example usage

Convert the file, retaining the source file

Convert-CertificateBinaryToBase64 -Sourcefile 'C:\myBinary.cer' -DestinationFile 'C:\myBase64.cer'

Convert the binary file, overwriting it with the Base64 file

Convert-CertificateBinaryToBase64 -Sourcefile 'C:\myCertificate.cer' -DestinationFile 'C:\myCertificate.cer'