|
95 | 95 | import re
|
96 | 96 | import sys
|
97 | 97 | import os
|
| 98 | +import io |
98 | 99 | from collections import namedtuple
|
99 | 100 | from enum import Enum as _Enum, IntEnum as _IntEnum, IntFlag as _IntFlag
|
100 | 101 |
|
@@ -450,6 +451,51 @@ def load_default_certs(self, purpose=Purpose.SERVER_AUTH):
|
450 | 451 | self._load_windows_store_certs(storename, purpose)
|
451 | 452 | self.set_default_verify_paths()
|
452 | 453 |
|
| 454 | + def load_cert_chain(self, certfile, keyfile=None, password=None): |
| 455 | + # If `certfile` is bytes or string, treat it as file path. |
| 456 | + if isinstance(certfile, str) or isinstance(certfile, bytes): |
| 457 | + certfile_path = certfile |
| 458 | + |
| 459 | + # If no `keyfile` is given, read private key from `certfile`. |
| 460 | + if keyfile is None: |
| 461 | + keyfile_path = certfile_path |
| 462 | + else: |
| 463 | + # If `certfile` is bytes or string, expect `keyfile` to be |
| 464 | + # a bytes or string file path, too. |
| 465 | + keyfile_path = keyfile |
| 466 | + |
| 467 | + # Pre CPython 3.7 behavior: let OpenSSL consume the files via |
| 468 | + # SSL_CTX_use_certificate_chain_file(). |
| 469 | + return self._load_cert_chain_pem_from_file_paths( |
| 470 | + certfile_path, keyfile_path, password) |
| 471 | + |
| 472 | + # Expect `certfile` to be a file object, expect `keyfile` to be `None` |
| 473 | + # or a file object. Read file(s) and prepare OpenSSL memory BIO |
| 474 | + # objects. If file objects return text, encode it to bytes. |
| 475 | + |
| 476 | + certdata = certfile.read() |
| 477 | + if isinstance(certdata, str): |
| 478 | + certdata = certdata.encode('utf-8') |
| 479 | + |
| 480 | + if keyfile is not None: |
| 481 | + keydata = keyfile.read() |
| 482 | + if isinstance(keydata, str): |
| 483 | + keydata = keydata.encode('utf-8') |
| 484 | + else: |
| 485 | + # Expect that `certdata` contains the private key, too. |
| 486 | + keydata = certdata |
| 487 | + |
| 488 | + certbio = MemoryBIO() |
| 489 | + certbio.write(certdata) |
| 490 | + certbio.write_eof() |
| 491 | + |
| 492 | + keybio = MemoryBIO() |
| 493 | + keybio.write(keydata) |
| 494 | + keybio.write_eof() |
| 495 | + |
| 496 | + return self._load_cert_chain_pem_from_bio(certbio, keybio, password) |
| 497 | + |
| 498 | + |
453 | 499 | @property
|
454 | 500 | def options(self):
|
455 | 501 | return Options(super().options)
|
|
0 commit comments