Bennett
Bennett

Reputation: 119

Export certificate from object with private key Export-Clixml

I'm trying to store a few objects as Clixml from PowerShell.

I can successfully store my array and certificate, but the private key is not exported with it.

Example:

PS > $cert.HasPrivateKey
true

PS > $outObject = $array
PS > $outObject += $cert
PS > $outObject | Export-Clixml -Path .\file.xml

PS > $inObject = Import-Clixml -Path .\file.xml
PS > $newcert = $inObject | Where-Object { $_.GetType().Name -like "*X509Certificate2" }

PS > $newcert.HasPrivateKey
false

I noted that there is a method for $cert.PrivateKey:

ExportParameters     Method     System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters)

This script is not specifically running in Windows and the certificate isn't installed in the CABI store, only the variable imported from Get-PfxCertificate.

Long story short, I'm building a module that connects to an API with client authentication. I'm trying to pull client authentication from the Clixml file.

Upvotes: 1

Views: 2428

Answers (2)

Bennett
Bennett

Reputation: 119

By converting the certificate object to PFX format (as suggested by Crypt32) and saving my objects in a hash table I was able to successfully export and import the array and certificate with private key.

PS > $cert.HasPrivateKey                                                             
true

PS > $pfx = $cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx,'Pa$$w0rd')
PS > $outObject = @{
>> myArray = $array
>> myCert = $pfx 
>> }

PS > Export-Clixml -InputObject $outObject -Path .\file.xml


PS > $inObject = Import-Clixml -Path .\file.xml   
PS > $newCert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::New($inObject.myCert,'Pa$$w0rd')
PS > $newCert.HasPrivateKey
true

Upvotes: 0

Crypt32
Crypt32

Reputation: 13954

The private key is not a part of X509Certificate2 object, thus it is not exported along with the public certificate. The private key is linked to the public certificate.

In order to export a certificate with a private key, you have to serialize the certificate and private key object before passing it to Export-CliXml.

Use the X509Certificate2.Export(X509Content​Type, Secure​String) method to export the certificate with the associated private key to PFX (PKCS#12 container). The private key material is password-protected.

Use the X509Certificate2.Import(Byte[], Secure​String, X509Key​Storage​Flags) method to import the certificate and associated private key after calling the Import-CliXml cmdlet.

This is the only option you have. Also, be aware that this approach works only when the private key is exportable. If the private key is non-exportable, the Export method will fail.

Upvotes: 1

Related Questions