Last active
March 19, 2020 01:25
-
-
Save shawmanz32na/8e947e3d5334fd0e7b25 to your computer and use it in GitHub Desktop.
Powershell script to extract DoD Certificates into a complete chain (for use with Apache), individual certificate files, and a Java Keystore containing the complete certificate chain (for use with Tomcat)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Exports the entire DoD CA Certificate chain as DoD_CAs.pem, and then exports the individual certificates to individual [CA].pem files, and imports them all into a Java Keystore called client.jks | |
Function Convert-DodCertBundleToIndivdualCerts { | |
[CmdletBinding()] | |
Param ( | |
[Parameter(Mandatory=$true)] | |
[String] | |
$Path, | |
[Parameter(Mandatory=$true)] | |
[String] | |
$Destination = "." | |
) | |
Begin{} | |
Process{ | |
# Create the destination directory if it doesn't exist yet | |
if (-Not (Test-Path $Destination)) { | |
New-Item -Name $Destination -ItemType directory | |
} | |
# TODO: Can we do this without exporting the entire chain? | |
Write-Host "Converting the DoD certificate bundle to PEM format..." | |
$certificateBundleFile = $Destination + "\" + "DoD_CA_Bundle.pem" | |
& openssl pkcs7 -in $Path -print_certs -out $certificateBundleFile | |
Write-Host "DoD certificate bundle converted to PEM format and saved as DoD_CA_Bundle.pem" | |
Write-Host "Identifying the individual DoD certificates..." | |
$certificateBundle = Get-Content $certificateBundleFile | Out-String | |
# Since -Split includes the match as a separate item, we use some regex trickery to match a zero-length section immediately after our intended match | |
$certificates = $certificateBundle -Split "(?<=" + "-----END CERTIFICATE-----" + [System.Environment]::NewLine + [System.Environment]::NewLine + ")" | |
Write-Host "Individual DoD certificates identified" | |
Write-Host -Object $certificates #Debug | |
Write-Host -Object $certificates[0] #Debug | |
foreach ($certificate in $certificates) { | |
# Get the name of the certificate so we can use it as a filename for the exported file | |
# Get the first line, which should be the Subject=blahblahCN=[caname] | |
$subjectLine = $certificate.Split([System.Environment]::NewLine)[0] | |
$subject = $subjectLine.Substring($subjectLine.LastIndexOf("=") + 1) | |
$certificateFile = $Destination + "/" + $subject.Trim().Replace(" ", "_") + ".pem" | |
Write-Host ("Writing " + $certificateFile + "...") | |
$certificate | Out-File -FilePath $certificateFile | |
} | |
Write-Host "Done!" | |
} | |
End{} | |
} | |
Export-ModuleMember -Function Convert-DodCertBundleToIndivdualCerts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment