grokgarble.com

Database, Software, and System Engineering

PEM Certificate from .NET/PowerShell

It is a tough thing – cryptography.  Especially when you try to standardize it enough for consumption among various components on hosted on multiple platforms.  Microsoft has done a good job of making their import features agnostic to file format.  Other platforms are not so forgiving and require it to be very specific based on function.  One of those specific formats is base64, with the appropriate line breaks, with a header and footer – or PEM.  This comes into play when you need to send a public certificate hosted on a Windows machine to a platform other than Windows, like an AS/400 mainframe for client certificate authentication.

PowerShell gives us the ability to quickly come up with an certificate object that is quite common on the Windows side: System.Security.Cryptography.X509Certificates.X509Certificate2.  To get there you can use the “cert” mount like this:

cd Cert:\CurrentUser\My

This allows you to get all certificates in your current user store and enumerate them as individual X509Certificate2 objects.  You can see them all once you’re here with a “DIR” or “Get-ChildItem” command to get a complete list of everything in the container.

To get a specific one stored into a variable use the handy Where-Object cmdlet like this:

$Cert = Get-ChildItem | where{ $_.Thumbprint -eq "DDC843EE6EFF730D4F5B87E2EF1212FB77223B27" }

If you want to confirm the type do a quick Get-Member (I do this so often to keep a bead on what I have available to me with a given object all the time)

$Cert | gm

Now, lets export the public certificate out as a base64 PEM with headers you’ll need to add them to the RawData property of the $Cert object:

$out = New-Object String[] -ArgumentList 3
$OutputFile = "C:\Temp\MyCertAsPEM.CER"

$out[0] = "-----BEGIN CERTIFICATE-----"
$out[1] = [System.Convert]::ToBase64String($Cert.PublicKey.EncodedKeyValue.RawData, "InsertLineBreaks")
$out[2] = "-----END CERTIFICATE-----"

[System.IO.File]::WriteAllLines($OutputFile,$out)

The above takes in account that you might have a private key and limits the output file to the public key only.

So, what about that pesky private key? Stay tuned..

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>