我正在编写一个需要从Windows上的证书存储区导出证书的Python程序。我已经尝试搜索执行此操作的代码段,但我找不到那样做的代码片段。这里重要的是我需要使用属于机器和当前用户的证书存储中的私钥导出证书。
=编辑以添加更多context =
我的目标是使用证书对Azure Key Vault进行身份验证。根据接受的答案,无法从Windows上的证书存储区检索证书。相反,我决定编写一个C#应用程序来验证Azure Key Vault并将秘密传递给Python应用程序。
您可以向powershell发送子进程调用,以从证书存储区导出证书。此脚本提示输入用户密码,然后将具有私钥的用户和localmachine证书存储中的证书导出为.pfx文件。
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()