Tuesday, May 18, 2021

PowerShell to check if private key is there in certificate

This is a small tip that can be considered as a continuation of an older post.  That was about validating the X509 certificate using PowerShell. As we all know, PowerShell is the way to execute almost anything in production, where using any other software is prohibited. 

The new problem encountered was that the certificate is there but no private key. When we use that certificate to obtain the Azure AAD token it fails. Below goes the snippet to check. 

(Get-ChildItem Cert:\CurrentUser\My | where {$_.Subject -match '<your subject>'}).HasPrivateKey

It's as simple as getting the object of the certificate using proper criteria. Then check the HasPrivateKey property. In order to get the certificate, the above snipper is using the subject. It can be changed to filter using Thumbprint and anything needed. In case of any queries please ask in the comments box.

If this is only one step to be done we may not require PowerShell. It can be checked using the system tools available in Windows. But this can be part of broader environment validation scripts where this helps to validate in a single click.

No comments: