As mentioned recently in a few posts, I’ve been writing a few scripts using Python over my usual PowerShell. I’m quickly realizing why I love PowerShell so much. It makes automation tasks so easy. Today’s challenge was programmatically getting a certificate out of the Windows Certificate Store using Python. In PowerShell it’s simply a couple of commands. Using Python however, there are a few packages that are required. They then return all the certificates in the store. You then need to iterate through them to find the one you’re after, versus just getting the one you want.
Now that I’ve gone through the pain of working it out for my requirements, I’m going to post it quickly here, as I know I’ll be needing to access the Windows Certificate Store using Python again in the future.
The core dependencies are the ‘wincertstore‘ and ‘cryptography‘ packages. These dependences can be installed using PIP.
pip install wincertstore cryptography
The following script will only work on a Windows host as it uses the wincertstore package to access the Windows Certificate Store and obtain all the certificates. There is a check in the script to verify it is being run on a windows host and it has only be tested using Python 3.8.
The script uses the ‘base64‘ and ‘ssl‘ libraries to decode each certificate and then compares each certificate to the ‘certName‘ and ‘thumbPrint‘ variables that define which certificate is looking to be returned. The details for that certificate are then output to the console. Update the certName and thumbPrint variables for the certificate you are looking to retrieve from the Windows Certificate Store.
Running the script will output the following information for the certificate specified using the certName and thumbPrint variables;
- serial number
- date issued
- expiry date
- subject alternate name(s)
- certificate usage
The screenshot below shows the script being executed.
I’m posting this to save myself a few hours next time I need to do this, and I’m sure it will help others too.