Share via


Display Subject Alternative Names of a Certificate with PowerShell

Subject Alternative Names (SANs) are stored as System.Security.Cryptography.X509Certificates.X509Extension objects in the PowerShell Certificate Provider.

First you can get the cert you want to view.

  $cert = get-childitem cert:\localmachine\my\73844B2206C170903185E777F65E969247462741

You can check the OID friendlyname of each extension to see where the subject alternative names reside, but simply viewing the extensions is not very useful since the RawData is encoded. So if the certificate that you assigned to $cert in the step above does include a subject alternative name, the command below will output a byte array, but not the human-readable text we are looking for.

  ($sanExt=$cert.Extensions | Where-Object {$_.Oid.FriendlyName -match "subject alternative name"}).RawData

However you can convert the ASN to a hex array and then decode it with the InitializeDecode method of the X509Enrollment.CX509ExtensionAlternativeNames COM object to get to human-readable text.

The whole script looks like this:

$cert=Get-ChildItem cert:\localmachine\my\73844B2206C170903185E777F65E969247462741            
$sanExt=$cert.Extensions | Where-Object {$_.Oid.FriendlyName -match "subject alternative name"}            
$sanObjs = new-object -ComObject X509Enrollment.CX509ExtensionAlternativeNames            
$altNamesStr=[System.Convert]::ToBase64String($sanExt.RawData)            
$sanObjs.InitializeDecode(1, $altNamesStr)            
Foreach ($SAN in $sanObjs.AlternativeNames) {$SAN.strValue}

Another option to display extension value in user-friendly format is to use standard .NET X509Extension::Format() (Inherited from AsnEncodedData.) method as follows:

$cert = Get-ChildItem cert:\localmachine\my\73844B2206C170903185E777F65E969247462741
$sanExt=$cert.Extensions | Where-Object {$_.Oid.FriendlyName -eq "subject alternative name"}
$sanExt.Format(1)

Or here's a simpler version:

$cert = Get-ChildItem cert:\localmachine\my\73844B2206C170903185E777F65E969247462741
($cert.Extensions | Where-Object {$_.Oid.FriendlyName -eq "subject alternative name"}).Format(1)

 

See Also