- 1 year ago
Python: How can I combine requests and windows certificate store for Client Side Certificates
To combine the requests
library with the Windows certificate store for client-side certificates in Python, you can use the win32crypt
module from the pywin32
package. Here's an example of how you can achieve this:
pythonimport requests
import win32crypt
# Load the client-side certificate from the Windows certificate store
cert_store = win32crypt.CertOpenSystemStore(None, "MY")
cert_thumbprint = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
cert_context = win32crypt.CertFindCertificateInStore(
cert_store,
win32crypt.X509_ASN_ENCODING | win32crypt.PKCS_7_ASN_ENCODING,
0,
win32crypt.CERT_FIND_SHA1_HASH,
win32crypt.CRYPT_HASH_BLOB,
bytes.fromhex(cert_thumbprint),
)
# Configure the requests library to use the client-side certificate
session = requests.Session()
session.cert = (
cert_context.CertStoreContext.Certificates[0].CertContext.pbCertEncoded,
cert_context.CertStoreContext.Certificates[0].CertContext.cbCertEncoded,
)
# Make a request using the client-side certificate
response = session.get("https://example.com")
# Process the response as needed
print(response.text)
In the above example:
The
win32crypt
module is imported from thepywin32
package to access the Windows certificate store.The
CertOpenSystemStore
function is used to open the "MY" certificate store, which represents the personal certificate store where client-side certificates are stored.The
CertFindCertificateInStore
function is called to find the client-side certificate in the certificate store based on its thumbprint (replace"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
with the actual thumbprint of your certificate).The
requests.Session
object is created, and thecert
attribute is set to the client-side certificate obtained from the Windows certificate store.A request is made using the
get
method of theSession
object, and the server will validate the client-side certificate during the SSL/TLS handshake.The response from the server is processed as needed.
Please make sure you have the pywin32
package installed (pip install pywin32
) and adjust the code according to your specific requirements, including the certificate store and thumbprint.