How to load all the certificates in a PEM-encoded certificate chain?

Viewed 1584

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.

1 Answers

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
Related