Created
August 30, 2018 16:13
-
-
Save bgelens/6d10931e50fde8e9437aa22e840a46de to your computer and use it in GitHub Desktop.
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
[cmdletbinding()] | |
param ( | |
[Parameter(Mandatory)] | |
[string] $Path, | |
[Parameter(Mandatory)] | |
[string] $PFXPin | |
) | |
$resolvedPath = Resolve-Path -Path $Path | |
$outputPath = Split-Path -Path $resolvedPath | |
Write-Warning -Message "Files will be written to $outputPath. Existing files will be overwritten!" | |
$certCollection = [System.Security.Cryptography.X509Certificates.X509Certificate2Collection]::new() | |
$certCollection.Import( | |
$resolvedPath.Path, | |
$PFXPin, | |
[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable | |
) | |
$certChain = [System.Text.StringBuilder]::new() | |
$pubKey = [System.Text.StringBuilder]::new() | |
$privKey = [System.Text.StringBuilder]::new() | |
$certCollection.ForEach{ | |
if ($_.hasprivatekey) { | |
Write-Verbose "$($_.subject) has been detected as the leaf and will be exported as public.cer and private.key" | |
[void] $pubKey.AppendLine('-----BEGIN CERTIFICATE-----') | |
[void] $pubKey.AppendLine(([convert]::ToBase64String($_.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert), [Base64FormattingOptions]::InsertLineBreaks))) | |
[void] $pubKey.AppendLine('-----END CERTIFICATE-----') | |
$privateKeyFromCert = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($_) | |
[void] $privKey.AppendLine('-----BEGIN RSA PRIVATE KEY-----') | |
[void] $privKey.AppendLine(([System.Convert]::ToBase64String($privateKeyFromCert.Key.Export([System.Security.Cryptography.CngKeyBlobFormat]::Pkcs8PrivateBlob), [System.Base64FormattingOptions]::InsertLineBreaks))) | |
[void] $privKey.AppendLine('-----END RSA PRIVATE KEY-----') | |
} else { | |
Write-Verbose "$($_.subject) has been detected as a ca and will be part of the cachain.cer" | |
[void] $certChain.AppendLine('-----BEGIN CERTIFICATE-----') | |
[void] $certChain.AppendLine(([convert]::ToBase64String($_.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert), [Base64FormattingOptions]::InsertLineBreaks))) | |
[void] $certChain.AppendLine('-----END CERTIFICATE-----') | |
} | |
} | |
$certChain.ToString() | Out-File -FilePath (Join-Path -Path $outputPath -ChildPath 'cachain.cer') -Encoding utf8 -Force | |
$pubKey.ToString() | Out-File -FilePath (Join-Path -Path $outputPath -ChildPath 'public.cer') -Encoding utf8 -Force | |
$privKey.ToString() | Out-File -FilePath (Join-Path -Path $outputPath -ChildPath 'private.key') -Encoding utf8 -Force |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment