4

When I use OpenSSL.crypto.load_certificate(b'< PEM encoded certificate bytes >') function on a PEM encoded full certificate chain, only the first certificate is loaded as a OpenSSL.crypto.X509 object.

The remaining certificates are completely ignored. I assume this is because the parser hits "END CERTIFICATE" and stop reading. Is there a utility function in OpenSSL (or elsewhere) which parses and loads the entire certificate chain?

By a "full certificate chain" I mean a PEM formatted certificate containing multiple ----- BEGIN CERTIFICATE ----- / ----- END CERTIFICATE ----- markers.

Chris W.
  • 37,583
  • 36
  • 99
  • 136

2 Answers2

7

This answer won't be fully applicable until the next cryptography release (39), but you can now do this with cryptography.x509.load_pem_x509_certificates:

from cryptography import x509

certs = x509.load_pem_x509_certificates(b"...")

That API will return a list of one or more certificates in the input, or it'll raise an exception if no valid certificate PEMs are present.

yossarian
  • 1,537
  • 14
  • 21
5

Here is a short snippet that reads all certificates from a PEM-encoded byte buffer:

start_line = b'-----BEGIN CERTIFICATE-----'

def read_all_certs(pem_bytes):
    result = []
    cert_slots = pem_bytes.split(start_line)
    for single_pem_cert in cert_slots[1:]:
        cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, start_line+single_pem_cert)
        result.append(cert)
    return result
Pak Uula
  • 2,750
  • 1
  • 8
  • 13