Powershell: Define a x509 certificate in a script

Hi,

the best way to store a certificate in a powershell script is in an byte array. But how to get such a byte array as string from an existing certificate?

First load the certificate from a file

PS D:\> $oMyCert=new-object System.Security.Cryptography.X509Certificates.X509Certificate2("D:\user\myCert.cer")

Then print out the array as string (Output shortend)

PS D:\> [string]::Join(",",$oMyCert.RawData)
48,130,4,151,48,130,3,127,160,3,2,1,2,2,20,37,238,178,117,203,149,76,144,234,220,33,66,40,173,193,73,57,107,211,105,48,13,6,9,42,134,72,134,247,13,1,1,11,5,0,48,129,173,49,11,48,9,6,3,85,4,6,19,2,68,69,49,16,48,14,6,3,85,4,8,12,7,71,101,114,109,97,110,.....

Copy the output from the console to define a byte array variable in your script (certificate shortend). To select a text in powershell by lines hold the ALT key pressed while selecting.

[byte[]]$aMyCert=@(48,130,4,151,48,130,3,127,......)

In your script create a X509 object by

$oMyCert=new-object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @(,$aMyCert)

Importend is to submit the byte array argument by the -ArgumentList switch otherwise the X509Certificate2 constructor recognizes each item of the array as argument. This would result in an error:

Cannot find an overload for “X509Certificate2” and the argument count: “1120”

Michael

Leave a Reply Cancel reply