Mark Delphi
Mark Delphi

Reputation: 1765

How to export certs with SAN extensions?

I have this PowerShell command that exports for me all issued certificates into a .csv file:

$Local = "$PSScriptRoot"

$File = "$Local\IssuedCerts.csv"

$Header = "Request ID,Requester Name,Certificate Template,Serial Number,Certificate Effective Date,Certificate Expiration Date,Issued Country/Region,Issued Organization,Issued Organization Unit,Issued Common Name,Issued City,Issued State,Issued Email Address"

certutil -view -out $Header csv > $File

This works fine. I would like to format the output in a more readable manner, if it's somehow possible, please let me know, too.

The point is I need to export all certificates which will expire soon, but I also need data from SAN Extensions from each certificate to be exported with.

Upvotes: 1

Views: 999

Answers (1)

NiMux
NiMux

Reputation: 1106

Perhaps getting the certificates directly from the CertificateAuthority X509Store and reading the certificate extensions (one of which is the Subject Alt Names) using the ASNEncodedData class would do the trick?

Example code below on reading certificates from the given store and printing out their extensions:

using namespace System.Security.Cryptography.X509Certificates

$caStore = [X509Store]::new([StoreName]::CertificateAuthority, [StoreLocation]::LocalMachine)
$caStore.Open([OpenFlags]::ReadOnly)

foreach ($certificate in $caStore.Certificates) {
   foreach ($extension in $certificate.Extensions) {
      $asnData = [System.Security.Cryptography.AsnEncodedData]::new($extension.Oid, $extension.RawData)
      Write-Host "Extension Friendly Name: $($extension.Oid.FriendlyName)"
      Write-Host "Extension OID: $($asnData.Oid.Value)"
      Write-Host "Extension Value: $($asnData.Format($true))"
   }
}

$caStore.Close()

You can specify a different store to open by specifying a different value for the [StoreName]::CertificateAuthority section.

Disclaimer, I haven't been able to test this code in production, so I'm not 100% certain that all the fields you require are exposed, but may serve as a good starting point

Upvotes: 2

Related Questions