Windows – How to remove the CA root certificate from a pfx file in Windows

opensslSecuritysslssl-certificatewindows

On a windows 2012 R2 and a Windows 10 machine there is a pfx file which contains the certificate chain for the server. I created this file using Windows MMC certificate export tool. The choices were export all certificates in the chain if possible or only the one certificate. The chain contains the root, two intermediary and then my server certificate.

I would like to remove the CA root certificate since the client should already have it, but leave the intermediary certificates.

How do you edit a pfx file to remove the one root certificate?

Best Answer

You can do this with few lines of PowerShell code (no OpenSSL is required):

$path = "Put the path to a pfx file here"
$password = "Put password here"
$pfx = New-Object Security.Cryptography.X509Certificates.X509Certificate2Collection
# import pfx to X509Certificate2 collection
$pfx.Import([IO.File]::ReadAllBytes($path), $password, "Exportable")
# remove first root (self-signed) certificate
if ($pfx.Count -gt 1) {
    for ($i = 0; $i -lt $pfx.Count; $i++) {
        if ($pfx[$i].Issuer -eq $pfx[$i].Subject) {
            [void]$pfx.RemoveAt($i); break
        }
    }
}
# write back pfx to a file
$bytes = $pfx.Export("pfx", $password)
[IO.File]::WriteAllBytes($path, $bytes)