Public/Extract-PfxCerts.ps1
<#
.SYNOPSIS This function uses openssl.exe to extract all public certificates and private key from a .pfx file. Each public certificate and the private key is written to its own separate file in the specified. OutputDirectory. If openssl.exe is not available on the current system, it is downloaded to the Current User's Downloads folder and added to $env:Path. NOTE: Nothing is installed. .DESCRIPTION See SYNOPSIS. .NOTES Depends on openssl.exe. NOTE: Nothing needs to be installed in order to use openssl.exe. .PARAMETER PFXFilePath Mandatory. This parameter takes a string that represents the full path to a .pfx file .PARAMETER PFXFilePwd Optional. This parameter takes a string (i.e. plain text password) or a secure string. If the private key in the .pfx file is password protected, use this parameter. .PARAMETER StripPrivateKeyPwd Optional. This parameter takes a boolean $true or $false. By default, this function writes the private key within the .pfx to a file in a protected format, i.e. -----BEGIN PRIVATE KEY----- -----END PRIVATE KEY----- If you set this parameter to $true, then this function will ALSO (in addition to writing out the above protected format to its own file) write the unprotected private key to its own file with format -----BEGIN RSA PRIVATE KEY---- -----END RSA PRIVATE KEY---- WARNING: This parameter is set to $true by default. .PARAMETER OutputDirectory Optional. This parameter takes a string that represents a file path to a *directory* that will contain all file outputs. If this parameter is not used, all file outputs are written to the same directory as the .pfx file. .PARAMETER DownloadAndAddOpenSSLToPath Optional. This parameter downloads openssl.exe from https://indy.fulgan.com/SSL/ to the current user's Downloads folder, and adds openssl.exe to $env:Path. WARNING: If openssl.exe is not already part of your $env:Path prior to running this function, this parameter becomes MANDATORY, or the function will fail. .EXAMPLE # If your private key is password protected... $PSSigningCertFile = "C:\Certs\Testing2\ZeroCode.pfx" $PFXSigningPwdAsSecureString = Read-Host -Prompt "Please enter the private key's password" -AsSecureString $OutDir = "C:\Certs\Testing2" Extract-PFXCerts -PFXFilePath $PSSigningCertFile ` -PFXFilePwd $PFXSigningPwdAsSecureString ` -StripPrivateKeyPwd $true ` -OutputDirectory $OutDir .EXAMPLE # If your private key is NOT password protected... $PSSigningCertFile = "C:\Certs\Testing2\ZeroCode.pfx" $OutputDirectory = "C:\Certs\Testing2" Extract-PFXCerts -PFXFilePath $PSSigningCertFile ` -StripPrivateKeyPwd $true ` -OutputDirectory $OutDir #> function Extract-PfxCerts { [CmdletBinding( PositionalBinding=$true, ConfirmImpact='Medium' )] Param( [Parameter(Mandatory=$False)] [string]$PFXFilePath = $(Read-Host -Prompt "Please enter the full path to the .pfx file."), [Parameter(Mandatory=$False)] $PFXFilePwd, # This is only needed if the .pfx contains a password-protected private key, which should be the case 99% of the time [Parameter(Mandatory=$False)] [bool]$StripPrivateKeyPwd = $true, [Parameter(Mandatory=$False)] [string]$OutputDirectory, # If this parameter is left blank, all output files will be in the same directory as the original .pfx [Parameter(Mandatory=$False)] [switch]$DownloadAndAddOpenSSLToPath ) ##### BEGIN Variable/Parameter Transforms and PreRun Prep ##### # Check for Win32 or Win64 OpenSSL Binary if (! $(Get-Command openssl.exe -ErrorAction SilentlyContinue)) { Write-Host "Downloading openssl.exe from http://wiki.overbyte.eu/wiki/index.php/ICS_Download..." [Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls" $OpenSSLWinBinariesUrl = "http://wiki.overbyte.eu/wiki/index.php/ICS_Download" $IWRResult = Invoke-WebRequest -Uri $OpenSSLWinBinariesUrl -ErrorAction Stop $LatestOpenSSLWinBinaryLinkObj = $($IWRResult.Links | Where-Object {$_.innerText -match "OpenSSL Binaries" -and $_.href -match "\.zip"})[0] $LatestOpenSSLWinBinaryUrl = $LatestOpenSSLWinBinaryLinkObj.href $OutputFileName = $($LatestOpenSSLWinBinaryUrl -split '/')[-1] $OutputFilePath = "$HOME\Downloads\$OutputFileName" Invoke-WebRequest -Uri $LatestOpenSSLWinBinaryUrl -OutFile $OutputFilePath if (!$(Test-Path "$HOME\Downloads\$OutputFileName")) { Write-Error "Problem downloading the latest OpenSSL Windows Binary from $LatestOpenSSLWinBinaryUrl ! Halting!" $global:FunctionResult = "1" return } $OutputFileItem = Get-Item $OutputFilePath $ExpansionDirectory = $OutputFileItem.Directory.FullName + "\" + $OutputFileItem.BaseName if (!$(Test-Path $ExpansionDirectory)) { $null = New-Item -ItemType Directory -Path $ExpansionDirectory -Force } else { Remove-Item "$ExpansionDirectory\*" -Recurse -Force } $null = Expand-Archive -Path "$HOME\Downloads\$OutputFileName" -DestinationPath $ExpansionDirectory -Force $FilesToCopy = Get-ChildItem -Path $ExpansionDirectory -File | Where-Object {$_.Name -notmatch "LICENSE" -and $_.Name -notmatch "readme"} foreach ($filetocopy in $FilesToCopy) { Copy-Item -Path "$($filetocopy.FullName)" -Destination "C:\Windows\System32\$($filetocopy.Name)" -Force } # Add $ExpansionDirectory to $env:Path <# $CurrentEnvPathArray = $env:Path -split ";" if ($CurrentEnvPathArray -notcontains $ExpansionDirectory) { # Place $ExpansionDirectory at start so latest openssl.exe get priority $env:Path = "$ExpansionDirectory;$env:Path" } #> if (![bool]$(Get-Command openssl -ErrorAction SilentlyContinue)) { Write-Error "Problem finding setting openssl after install! Halting!" $global:FunctionResult = "1" return } } # OpenSSL can't handle PowerShell SecureStrings, so need to convert it back into Plain Text if ($PFXFilePwd) { if ($PFXFilePwd.GetType().FullName -eq "System.Security.SecureString") { $PwdForPFXOpenSSL = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($PFXFilePwd)) } if ($PFXFilePwd.GetType().FullName -eq "System.String") { $PwdForPFXOpenSSL = $PFXFilePwd } } $privpos = $PFXFilePath.LastIndexOf("\") $PFXFileDir = $PFXFilePath.Substring(0, $privpos) $PFXFileName = $PFXFilePath.Substring($privpos+1) $PFXFileNameSansExt = $($PFXFileName.Split("."))[0] if (!$OutputDirectory) { $OutputDirectory = $PFXFileDir } $ProtectedPrivateKeyOut = "$PFXFileNameSansExt"+"_protected_private_key"+".pem" $UnProtectedPrivateKeyOut = "$PFXFileNameSansExt"+"_unprotected_private_key"+".pem" $AllPublicKeysInChainOut = "$PFXFileNameSansExt"+"_all_public_keys_in_chain"+".pem" ##### END Variable/Parameter Transforms and PreRun Prep ##### ##### BEGIN Parameter Validation ##### if (!$(Test-Path $PFXFilePath)) { Write-Error "The path $PFXFilePath was not found! Halting!" $global:FunctionResult = "1" return } if (! $(Test-Path $OutputDirectory)) { Write-Error "The path $OutputDirectory was not found! Halting!" $global:FunctionResult = "1" return } ##### END Parameter Validation ##### ##### BEGIN Main Body ##### # The .pfx File could (and most likely does) contain a private key # Extract Private Key and Keep It Password Protected try { $ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo $ProcessInfo.FileName = "openssl.exe" $ProcessInfo.RedirectStandardError = $true $ProcessInfo.RedirectStandardOutput = $true $ProcessInfo.UseShellExecute = $false $ProcessInfo.Arguments = "pkcs12 -in $PFXFilePath -nocerts -out $OutputDirectory\$ProtectedPrivateKeyOut -nodes -password pass:$PwdForPFXOpenSSL" $Process = New-Object System.Diagnostics.Process $Process.StartInfo = $ProcessInfo $Process.Start() | Out-Null $Process.WaitForExit() $stdout = $Process.StandardOutput.ReadToEnd() $stderr = $Process.StandardError.ReadToEnd() $AllOutput = $stdout + $stderr if ($AllOutput -match "error") { Write-Warning "openssl.exe reports that -PFXFilePwd is incorrect. However, it may be that at this stage in the process, it is not protected with a password. Trying without password..." throw } } catch { try { $ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo $ProcessInfo.FileName = "openssl.exe" $ProcessInfo.RedirectStandardError = $true $ProcessInfo.RedirectStandardOutput = $true $ProcessInfo.UseShellExecute = $false $ProcessInfo.Arguments = "pkcs12 -in $PFXFilePath -nocerts -out $OutputDirectory\$ProtectedPrivateKeyOut -nodes -password pass:" $Process = New-Object System.Diagnostics.Process $Process.StartInfo = $ProcessInfo $Process.Start() | Out-Null $Process.WaitForExit() $stdout = $Process.StandardOutput.ReadToEnd() $stderr = $Process.StandardError.ReadToEnd() $AllOutput = $stdout + $stderr if ($AllOutput -match "error") { Write-Warning "openssl.exe reports that -PFXFilePwd is incorrect." throw } } catch { $PFXFilePwdFailure = $true } } if ($PFXFilePwdFailure -eq $true) { Write-Verbose "The value for -PFXFilePwd is incorrect or was not supplied (and is needed). Halting!" Write-Error "The value for -PFXFilePwd is incorrect or was not supplied (and is needed). Halting!" $global:FunctionResult = "1" return } if ($StripPrivateKeyPwd) { # Strip Private Key of Password #& openssl.exe rsa -in "$PFXFileDir\$ProtectedPrivateKeyOut" -out "$OutputDirectory\$UnProtectedPrivateKeyOut" 2>&1 | Out-Null try { $ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo $ProcessInfo.FileName = "openssl.exe" $ProcessInfo.RedirectStandardError = $true $ProcessInfo.RedirectStandardOutput = $true $ProcessInfo.UseShellExecute = $false $ProcessInfo.Arguments = 'rsa -in "{0}" -out "{1}"' -f "$PFXFileDir\$ProtectedPrivateKeyOut","$OutputDirectory\$UnProtectedPrivateKeyOut" $Process = New-Object System.Diagnostics.Process $Process.StartInfo = $ProcessInfo $Process.Start() | Out-Null $Process.WaitForExit() $stdout = $Process.StandardOutput.ReadToEnd() $stderr = $Process.StandardError.ReadToEnd() $AllOutput = $stdout + $stderr if ($AllOutput -match "error") { Write-Warning "openssl.exe reports that -PFXFilePwd is incorrect. However, it may be that at this stage in the process, it is not protected with a password. Trying without password..." throw } } catch { $StripPrivateKeyPwdFailure = $true } } New-Variable -Name "$PFXFileNameSansExt`PrivateKeyInfo" -Value $( if ($StripPrivateKeyPwd) { [pscustomobject][ordered]@{ ProtectedPrivateKeyFilePath = "$OutputDirectory\$ProtectedPrivateKeyOut" UnProtectedPrivateKeyFilePath = "$OutputDirectory\$UnProtectedPrivateKeyOut" } } else { [pscustomobject][ordered]@{ ProtectedPrivateKeyFilePath = "$OutputDirectory\$ProtectedPrivateKeyOut" UnProtectedPrivateKeyFilePath = $null } } ) # Setup $ArrayOfPubCertPSObjects for PSCustomObject Collection $ArrayOfPubCertPSObjects = @() # The .pfx File Also Contains ALL Public Certificates in Chain # The below extracts ALL Public Certificates in Chain try { $ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo $ProcessInfo.FileName = "openssl.exe" $ProcessInfo.RedirectStandardError = $true $ProcessInfo.RedirectStandardOutput = $true $ProcessInfo.UseShellExecute = $false $ProcessInfo.Arguments = "pkcs12 -in $PFXFilePath -nokeys -out $OutputDirectory\$AllPublicKeysInChainOut -password pass:$PwdForPFXOpenSSL" $Process = New-Object System.Diagnostics.Process $Process.StartInfo = $ProcessInfo $Process.Start() | Out-Null $Process.WaitForExit() $stdout = $Process.StandardOutput.ReadToEnd() $stderr = $Process.StandardError.ReadToEnd() $AllOutput = $stdout + $stderr if ($AllOutput -match "error") { Write-Warning "openssl.exe reports that -PFXFilePwd is incorrect. However, it may be that at this stage in the process, it is not protected with a password. Trying without password..." throw } } catch { try { $ProcessInfo = New-Object System.Diagnostics.ProcessStartInfo $ProcessInfo.FileName = "openssl.exe" $ProcessInfo.RedirectStandardError = $true $ProcessInfo.RedirectStandardOutput = $true $ProcessInfo.UseShellExecute = $false $ProcessInfo.Arguments = "pkcs12 -in $PFXFilePath -nokeys -out $OutputDirectory\$AllPublicKeysInChainOut -password pass:" $Process = New-Object System.Diagnostics.Process $Process.StartInfo = $ProcessInfo $Process.Start() | Out-Null $Process.WaitForExit() $stdout = $Process.StandardOutput.ReadToEnd() $stderr = $Process.StandardError.ReadToEnd() $AllOutput = $stdout + $stderr if ($AllOutput -match "error") { Write-Warning "openssl.exe reports that -PFXFilePwd is incorrect." throw } } catch { $PFXFilePwdFailure = $true } } if ($PFXFilePwdFailure -eq $true) { Write-Verbose "The value for -PFXFilePwd is incorrect or was not supplied (and is needed). Halting!" Write-Error "The value for -PFXFilePwd is incorrect or was not supplied (and is needed). Halting!" $global:FunctionResult = "1" return } New-Variable -Name "CertObj$PFXFileNameSansExt" -Scope Script -Value $( [pscustomobject][ordered]@{ CertName = "$PFXFileNameSansExt`AllPublicKCertsInChain" AllCertInfo = Get-Content "$OutputDirectory\$AllPublicKeysInChainOut" FileLocation = "$OutputDirectory\$AllPublicKeysInChainOut" } ) -Force $ArrayOfPubCertPSObjects +=, $(Get-Variable -Name "CertObj$PFXFileNameSansExt" -ValueOnly) # Parse the Public Certificate Chain File and and Write Each Public Certificate to a Separate File # These files should have the EXACT SAME CONTENT as the .cer counterparts $PublicKeySansChainPrep1 = $(Get-Content "$OutputDirectory\$AllPublicKeysInChainOut") -join "`n" $PublicKeySansChainPrep2 = $($PublicKeySansChainPrep1 -replace "-----END CERTIFICATE-----","-----END CERTIFICATE-----;;;").Split(";;;") $PublicKeySansChainPrep3 = foreach ($obj1 in $PublicKeySansChainPrep2) { if ($obj1 -like "*[\w]*") { $obj1.Trim() } } # Setup PSObject for Certs with CertName and CertValue foreach ($obj1 in $PublicKeySansChainPrep3) { $CertNamePrep = $($obj1).Split("`n") | foreach {if ($_ | Select-String "subject") {$_}} $CertName = $($CertNamePrep | Select-String "CN=([\w]|[\W]){1,1000}$").Matches.Value -replace "CN=","" $IndexNumberForBeginCert = $obj1.Split("`n") | foreach { if ($_ -match "-----BEGIN CERTIFICATE-----") { [array]::indexof($($obj1.Split("`n")),$_) } } $IndexNumberForEndCert = $obj1.Split("`n") | foreach { if ($_ -match "-----End CERTIFICATE-----") { [array]::indexof($($obj1.Split("`n")),$_) } } $CertValue = $($($obj1.Split("`n"))[$IndexNumberForBeginCert..$IndexNumberForEndCert] | Out-String).Trim() $AttribFriendlyNamePrep = $obj1.Split("`n") | Select-String "friendlyName" if ($AttribFriendlyNamePrep) { $AttribFriendlyName = $($AttribFriendlyNamePrep.Line).Split(":")[-1].Trim() } $tmpFile = [IO.Path]::GetTempFileName() $CertValue.Trim() | Out-File $tmpFile -Encoding Ascii $CertDumpContent = certutil -dump $tmpfile $SubjectTypePrep = $CertDumpContent | Select-String -Pattern "Subject Type=" if ($SubjectTypePrep) { $SubjectType = $SubjectTypePrep.Line.Split("=")[-1] } $RootCertFlag = $CertDumpContent | Select-String -Pattern "Subject matches issuer" $SubjectCheck = $($obj1.Trim() -split "`n" | Select-String subject) -replace 'subject','' $IssuerCheck = $($obj1.Trim() -split "`n" | Select-String issuer) -replace 'issuer','' if ($SubjectType -eq "CA" -and $RootCertFlag -or $SubjectCheck -eq $IssuerCheck) { $RootCACert = $True } else { $RootCACert = $False } if ($SubjectType -eq "CA" -and !$RootCertFlag) { $IntermediateCACert = $True } else { $IntermediateCACert = $False } if ($RootCACert -eq $False -and $IntermediateCACert -eq $False) { $EndPointCert = $True } else { $EndPointCert = $False } New-Variable -Name "CertObj$CertName" -Scope Script -Value $( [pscustomobject][ordered]@{ CertName = $CertName FriendlyName = $AttribFriendlyName CertValue = $CertValue.Trim() AllCertInfo = $obj1.Trim() RootCACert = $RootCACert IntermediateCACert = $IntermediateCACert EndPointCert = $EndPointCert FileLocation = "$OutputDirectory\$($CertName)_Public_Cert.pem" } ) -Force $ArrayOfPubCertPSObjects +=, $(Get-Variable -Name "CertObj$CertName" -ValueOnly) Remove-Item -Path $tmpFile -Force Remove-Variable -Name "tmpFile" -Force } # Write each CertValue to Separate Files (i.e. writing all public keys in chain to separate files) foreach ($obj1 in $ArrayOfPubCertPSObjects) { if ($(Test-Path $obj1.FileLocation) -and !$Force) { #Write-Verbose "The extracted Public cert $($obj1.CertName) was NOT written to $OutputDirectory because it already exists there!" # Append $obj.FileLocation $AppendString = '_' + $([IO.Path]::GetRandomFileName()[0..3] -join '') + '.pem' $OutFilePath = $obj1.FileLocation -replace '\.pem',$AppendString $obj1.CertValue | Out-File $OutFilePath -Encoding Ascii } if (!$(Test-Path $obj1.FileLocation) -or $Force) { $OutFilePath = $obj1.FileLocation $obj1.CertValue | Out-File $OutFilePath -Encoding Ascii } $FileItem = Get-Item $OutFilePath if ($FileItem.Length -eq 0) { $null = Remove-Item $FileItem } } Write-Verbose "Public certs have been extracted and written to $OutputDirectory" New-Variable -Name "PubAndPrivInfoOutput" -Scope Script -Value $( [pscustomobject][ordered]@{ PublicKeysInfo = $ArrayOfPubCertPSObjects PrivateKeyInfo = $(Get-Variable -Name "$PFXFileNameSansExt`PrivateKeyInfo" -ValueOnly) } ) -Force $(Get-Variable -Name "PubAndPrivInfoOutput" -ValueOnly) $global:FunctionResult = "0" ##### END Main Body ##### } |