Author Posts

September 19, 2016 at 9:04 pm

How do I export a certificate using Base 64 .CER format with PowerShell ?
The Export-Certificate cmdlet has a 'Type' parameter with a P7B value, but I'm not sure if that's the same as selecting the 'Base-64 encoded X.509 (.CER)' radio button in the 'Certificate Export Wizard' using the GUI (see screenshot below)

Screenshot

September 20, 2016 at 1:18 pm

P7B is binary bundle of certificates which is not what you're looking for. Unfortunately, the Export-Certificate cmdlet does not offer the "Base-64 encoded X.509 (.CER)" type to be exported but you can use below snippet to get the job done.

$cert = Get-Item -Path Cert:\LocalMachine\CA\D559A586669B08F46A30A133F8A9ED3D038E2EA8
$certFile = 'C:\My\exported.cer'

$content = @(
    '-----BEGIN CERTIFICATE-----'
    [System.Convert]::ToBase64String($cert.RawData, 'InsertLineBreaks')
    '-----END CERTIFICATE-----'
)

$content | Out-File -FilePath $certFile -Encoding ascii

September 25, 2016 at 6:45 pm

Thanks Daniel.

I found that 'certutil -encode' can also be used for exporting to Base64 format.

I noticed that exporting to Base64 format using both 'certutil -encode' and the MMC Certificate GUI adds the 'BEGIN/END CERTIFICATE' tags, and adds line breaks after 65 characters. And with ToBase64String, the InsertLineBreaks parameter adds line breaks after 76 characters, and the 'BEGIN/END CERTIFICATE' tags need to be hand-coded.

I know the line breaks shouldn't matter, but just to retain compatibility with the native Windows way in which Base64 certificates are exported, I ended up using the following code:

$cert = Get-ChildItem Cert:\LocalMachine\My | where { $_.Subject -imatch 'mydomain\.com' }
$DERCert    = 'C:\Cert_DER_Encoded.cer'
$Base64Cert = 'C:\Cert_Base64_Encoded.cer' 
Export-Certificate -Cert $cert -FilePath $DERCert
Start-Process -FilePath 'certutil.exe' -ArgumentList "-encode $DERCert $Base64Cert" -WindowStyle Hidden

Thanks,
Mario