Export certificate using Base 64 .CER format with PowerShell ?

Welcome Forums General PowerShell Q&A Export certificate using Base 64 .CER format with PowerShell ?

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
2 years, 6 months ago.

  • Author
    Posts
  • #54286

    Participant
    Points: 1
    Rank: Member

    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

  • #54313

    Moderator
    Points: 24
    Team Member
    Rank: Member

    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
    
  • #54591

    Participant
    Points: 1
    Rank: Member

    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

The topic ‘Export certificate using Base 64 .CER format with PowerShell ?’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort