I manage the Domain Controllers centrally, but the site admins manage their own digital senders locally. I can easily export an X509 certificate (private key not needed) with the whole chain from a Windows Server 2008 R2 Domain Controller to a p7b file through the wizard:
~~~~~~~~~~~~~~~~~
...5. The Certificate Export Wizard opens. Click Next.
In the Export File Format dialog box, do the following:
a. Select Cryptographic Message Syntax Standard – PKCS #7 Certificates (.P7B).
b. Check Include all certificates in the certification path if possible.
c. Click Next.
In the File to Export dialog box, click Browse.
In the Save As dialog box, do the following:
a. In the File Name box, type ciroots.p7b.
b. In the Save as type box, select PKCS #7 Certificates (*.p7b).
c. Click Save.
In the File to Export dialog box, click Next.
On the Completing the Certificate Export Wizard page, click Finish.
~~~~~~~~~~~~~~~~~
It works great. The resulting file imports just fine into a digital sender for authentication. It gives the site admins access to the other certs in the chain if they have not already imported them. It does not need to contain the private key, since it works fine without it.
The trouble is, I would need to do this manually, literally dozens of times, once for each business site, since each has their own Domain Controllers, each with their own certificate. There must be a way I can automate this certificate export (PowerShell w/.NET, certutil.exe, etc.). Maybe something that uses System.Security.Cryptography.X509Certificates X509IncludeOption with WholeChain, but I can't get it to work:
$Cert = (dir Cert:\localmachine\my)[0]
# PKCS7 cert export with .p7b file extension.
$CertCollection = New-Object
System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$Cert | %{[void]$CertCollection.Add($_)}
$Exported_pkcs7 = $CertCollection.Export('Pkcs7')
$out_FileName = $ENV:COMPUTERNAME + ".p7b"
$My_Export_Path = 'd:\CertFiles\' + $out_FileName
Set-Content -path $My_Export_Path -Value $Exported_pkcs7 -encoding Byte
With this code, I only get the certificate, not the rest of the certificates in its chain. I don't need the whole script, just the part that duplicates the export w/chain that I can already do manually through the GUI.