Search for certificates by serial number (or any other property)

comments

Powershell Logo

What if you'd like to check if some certificate is installed to current user certificates storage? What if the only thing you know about this certificate is serial number or thumbprint? What if there is more than one hundred certificates installed on machine?

You'll never find it manually by using Certificate Manager Tool (certmgr.msc), you need some automated solution.

Powershell is the right tool for this kind of administration on Windows. With powershell you can retrieve all current user certificates with

ls Cert:\LocalMachine\My\

ls is a the build-in alias for Get-ChildItem, and Cert:\LocalMachine\My\ is location which is contains current user certificates. In fact, all certificate objects from this location are instances of X509Certificate2 class.

Now, when we know how to enumerate all certificates, let's filter them in one-liner-manner using where-object:

ls Cert:\LocalMachine\My\ | where-object { $_.SerialNumber -eq '01f349e07ac40ccd80e8110ae70ff375b0'}

This will print on console Thumbprint and Subject of found certificate.

If we need to print something more than that, we can specify properties of certificate object using select clause:

ls Cert:\LocalMachine\My\ `
    | where-object { $_.SerialNumber -eq '01f349e07ac40ccd80e8110ae70ff375b0'} `
    | select Thumbprint, SerialNumber, NotAfter, Subject, @{n="SignatureAlgorithm";e={$_.SignatureAlgorithm.FriendlyName}}

Pay attention to strange @{n="SignatureAlgorithm";e={$_.SignatureAlgorithm.FriendlyName}} expression. This is abbreviation for calculated properties. With n we declare name for property, and e is arbitrary expression for the value. $_ stands for current value in the pipeline.

Also, I've used backtick (`) here to place the expression on multiple lines.

Summary

So, using select ... | where-object ... expressions you can filter your certificates by any property, static or computed. For example, by SignatureAlgorithm in example above. Or you could use very tricky filters using BouncyCastle library to extract specific certificate OID strings from X509Certificate2.RawData property if needed! Anything!

Happy scripting!


If you like this post, consider supporting me on liberapay

Comments