I'm writing a Python program that needs to export a certificate from a certificate store on Windows. I've tried searching for a code snippet that does this but I'm having trouble finding one that does that. The important thing here is that I need to export the certificate with the private key from certificate stores that belonging to the machine and the current user.
My goal was to use a certificate to authenticate to Azure Key Vault. Based on the accepted answer, there's no way to retrieve a certificate from a cert store on windows. I decided to, instead, write a C# app to authenticate to Azure Key Vault and pass the secrets to the Python application.
You could send a subprocess call to powershell to export the certificates from the certificate store. This script prompts for a user password, then exports the certificates from the user's and localmachine certificate store that have a private key as .pfx files.
import subprocess
import getpass
pw = getpass.getpass()
proc = subprocess.Popen(
[
'powershell.exe',
'-c',
f'&{{ $pw = ConvertTo-SecureString -String "{pw}" -Force -AsPlainText;',
'gci Cert:\\*\\My\\* |',
'?{ $_.HasPrivateKey } |',
'%{ Export-PfxCertificate -cert $_.PSPath',
'-FilePath $env:USERPROFILE\\$($_.thumbprint).pfx -Password $pw}',
'}'
],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
shell = True
)
out, err = proc.communicate()