diff --git a/Lib/ssl.py b/Lib/ssl.py index 5b8762bcdc25d1..cd81fcfa86f0a3 100644 --- a/Lib/ssl.py +++ b/Lib/ssl.py @@ -513,17 +513,29 @@ def set_alpn_protocols(self, alpn_protocols): self._set_alpn_protocols(protos) def _load_windows_store_certs(self, storename, purpose): + certs = [] try: for cert, encoding, trust in enum_certificates(storename): # CA certs are never PKCS#7 encoded if encoding == "x509_asn": if trust is True or purpose.oid in trust: - try: - self.load_verify_locations(cadata=cert) - except SSLError as exc: - warnings.warn(f"Bad certificate in Windows certificate store: {exc!s}") + certs.append(cert) except PermissionError: warnings.warn("unable to enumerate Windows certificate store") + if certs: + # Try to load all certificates at once, for performance. + try: + self.load_verify_locations(cadata=b''.join(certs)) + return + except SSLError: + pass + # There are invalid certificates. + # Load them one by one and ignore the bad ones. + for cert in certs: + try: + self.load_verify_locations(cadata=cert) + except SSLError as exc: + warnings.warn(f"Bad certificate in Windows certificate store: {exc!s}") def load_default_certs(self, purpose=Purpose.SERVER_AUTH): if not isinstance(purpose, _ASN1Object): diff --git a/Misc/NEWS.d/next/Library/2025-08-09-22-43-33.gh-issue-137560.JFUI4F.rst b/Misc/NEWS.d/next/Library/2025-08-09-22-43-33.gh-issue-137560.JFUI4F.rst new file mode 100644 index 00000000000000..dda389dee0cba1 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-08-09-22-43-33.gh-issue-137560.JFUI4F.rst @@ -0,0 +1,2 @@ +Speed up :func:`ssl.create_default_context` on Windows if all certificates +in the Windows certificate store are valid.