如何在python中使用来自Windows证书存储的客户端证书



我想使用存储在Windows证书存储中的客户端证书(公钥+私钥(来调用web请求。

使用PowerShell,我的调用将如下所示(有效(:
Invoke-WebRequest -CertificateThumbprint $thumbprint -Uri $uri

现在我正在python中寻找一个等价的。我不想提取证书并传递文件,而是直接使用存储,或者至少只将证书保存在内存中。

我尝试过wincertstore,但证书在UserStore(cert:\CurrentUser\My(中,所以我无法访问它。sslContext也有同样的问题。

在这个答案中提到的安装python-certificate-win32似乎只加载CA证书来验证服务器,但我需要的是一个客户端证书来验证自己与服务器的关系。

除了使用子流程调用powershell之外,还有其他方法可以实现这一点吗
非常感谢。

对于任何有同样问题的人。我使用clr将证书导出到内存中,并请求_toolbelt将其用于请求。

使其工作的代码示例:

import clr
import requests
import requests_toolbelt
from cryptography.hazmat.primitives.serialization.pkcs12 import load_key_and_certificates
from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption
from cryptography.hazmat.backends import default_backend
from requests_toolbelt.adapters.x509 import X509Adapter
clr.AddReference('System')
clr.AddReference('System.Linq')
clr.AddReference('System.Security.Cryptography.X509Certificates')
clr.AddReference('System.Security.Cryptography')
from System.Security.Cryptography.X509Certificates import X509Store, StoreName, StoreLocation,OpenFlags,X509Certificate2Collection,X509FindType,X509Certificate2, X509ContentType
from System.Security.Cryptography import AsymmetricAlgorithm
store = X509Store(StoreName.My, StoreLocation.CurrentUser)
store.Open(OpenFlags.ReadOnly)
user = os.environ['USERNAME']
certCollection = store.Certificates.Find(
X509FindType.FindBySubjectName,
user,
False)
cert = certCollection.get_Item(0)
pkcs12 = cert.Export(X509ContentType.Pkcs12, <passphrase>)
backend = default_backend()
pkcs12_password_bytes = "<password>".encode('utf8')
pycaP12 = load_key_and_certificates(pkcs12, pkcs12_password_bytes, backend)
cert_bytes = pycaP12[1].public_bytes(Encoding.DER)
pk_bytes = pycaP12[0].private_bytes(Encoding.DER, PrivateFormat.PKCS8, NoEncryption())
adapter = X509Adapter(max_retries=3, cert_bytes=cert_bytes, pk_bytes=pk_bytes, encoding=Encoding.DER)
session = requests.Session()
session.mount('https://', adapter)
session.get('url', verify=True)

最新更新