Skip to content

Instantly share code, notes, and snippets.

@JohnLBevan
Last active April 7, 2022 10:12
Show Gist options
  • Select an option

  • Save JohnLBevan/aa098281ba3e712369e7c7634a4e7446 to your computer and use it in GitHub Desktop.

Select an option

Save JohnLBevan/aa098281ba3e712369e7c7634a4e7446 to your computer and use it in GitHub Desktop.
Simple script to convert PEM to X509 Certs; useful if you want to check which certs a PEM relates to, or check the order of the certs in the chain.
function Convert-PemToX509Cert {
Param (
[Parameter(Mandatory)]
[string]$Path
,
[Parameter()]
[System.Text.Encoding]$Encoding = [System.Text.Encoding]::UTF8
)
$options = [System.Text.RegularExpressions.RegexOptions]::CultureInvariant -bor [System.Text.RegularExpressions.RegexOptions]::Singleline
$regex = [System.Text.RegularExpressions.RegEx]::new('\-{5}BEGIN CERTIFICATE\-{5}(?<CERT>.*?)\-{5}END CERTIFICATE\-{5}', $options)
$pemText = [System.IO.File]::ReadAllText($Path, $Encoding)
[string[]]$certs = $regex.Matches( $pemText ) | ForEach-Object {$_.Groups['CERT'].Value} | Where-Object {![string]::IsNullOrWhiteSpace($_)}
foreach ($cert in $certs) {
[byte[]]$certBytes = [System.Text.Encoding]::UTF8.GetBytes(($cert -replace '[\r\n\s]+', ''))
[Security.Cryptography.X509Certificates.X509Certificate2]::new($certBytes);
}
}
<#
# EXAMPLE:
Convert-PemToX509Cert -Path 'C:\Certbot\archive\example.com\fullchain1.pem' | ft Subject, Issuer
# OUTPUT:
# Subject Issuer
# ------- ------
# CN=*.example.com CN=R3, O=Let's Encrypt, C=US
# CN=R3, O=Let's Encrypt, C=US CN=ISRG Root X1, O=Internet Security Research Group, C=US
# CN=ISRG Root X1, O=Internet Security Research Group, C=US CN=DST Root CA X3, O=Digital Signature Trust Co.
#>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment