Skip to content

Commit d856204

Browse files
gh-137560: Speed up ssl.create_default_context() on Windows
Try to load all certificates at once. This speeds up the process if all certificates in the Windows certificate store are valid. But slows down it if there are invalid ones.
1 parent af15e1d commit d856204

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

Lib/ssl.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -513,17 +513,29 @@ def set_alpn_protocols(self, alpn_protocols):
513513
self._set_alpn_protocols(protos)
514514

515515
def _load_windows_store_certs(self, storename, purpose):
516+
certs = []
516517
try:
517518
for cert, encoding, trust in enum_certificates(storename):
518519
# CA certs are never PKCS#7 encoded
519520
if encoding == "x509_asn":
520521
if trust is True or purpose.oid in trust:
521-
try:
522-
self.load_verify_locations(cadata=cert)
523-
except SSLError as exc:
524-
warnings.warn(f"Bad certificate in Windows certificate store: {exc!s}")
522+
certs.append(cert)
525523
except PermissionError:
526524
warnings.warn("unable to enumerate Windows certificate store")
525+
if certs:
526+
# Try to load all certificates at once, for performance.
527+
try:
528+
self.load_verify_locations(cadata=b''.join(cert))
529+
return
530+
except SSLError:
531+
pass
532+
# There are invalid certificates.
533+
# Load them one by one and ignore the bad ones.
534+
for cert in certs:
535+
try:
536+
self.load_verify_locations(cadata=cert)
537+
except SSLError as exc:
538+
warnings.warn(f"Bad certificate in Windows certificate store: {exc!s}")
527539

528540
def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
529541
if not isinstance(purpose, _ASN1Object):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Speed up :func:`ssl.create_default_context` on Windows if all certificates
2+
in the Windows certificate store are valid.

0 commit comments

Comments
 (0)