VaM
VaM

Reputation: 310

Export root certificate using powershell

I am installing a client side certificate on a Windows 2012 server through Powershell. Installing a client side certificate requires two steps:

  1. Installing the certificate on the Personal Store ("my").
  2. Installing the root certificate of that certificate in the Trusted Root Certification Authority Store.

Step 1 is fairly easy. However, step 2 is tricky. First, I do not know the length of the chain of the certificate. When doing it by-hand, you need to go to export each certificate in the chain until you reach the root (you can only export the first element of the chain). Then, you install the root certificate in the Trusted Store.

So, my question is: how do you get the root certificate of a certificate? My idea would be to get the certificate chain and somehow process it until you get the root certificate. Any ideas on how this can be done?

Upvotes: 0

Views: 3975

Answers (1)

Stuart Anderson
Stuart Anderson

Reputation: 21

GodEater's advice helped me, by looking at this page https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates(v=vs.110).aspx I figured out how to do it:-

If you import your pkcs12 certificate into System.Security.Cryptography.X509Certificates.X509Certificate2Collection

When you take a look at the object both certificates are there, so simply looping through the object and adding each certificate to the correct store works:-

$fileName = "cert.p12";
$password = "Password"
$certRootStore = "localmachine";
$certStore = "Root";
$certStore2 = "My";
$X509Flags = "PersistKeySet,MachineKeySet";
$pfx = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection;
$pfx.Import($fileName, $Password, $X509Flags);
foreach ($cert in $pfx) {
    if ($cert.Subject -match "CN=Your Cert Auth Name") {
        $store = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Store -ArgumentList $certStore,$certRootStore;
        $store.Open("MaxAllowed");$store.Add($cert);
        $store.Close | Out-Null
    }
    else {
        $store = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Store -ArgumentList $certStore2,$certRootStore;
        $store.Open("MaxAllowed");
        $store.Add($cert);
        $store.Close | Out-Null
    }
}

Upvotes: 2

Related Questions