Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 234
Chris W. Avatar asked Sep 05 '25 03:09

Chris W.


2 Answers

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.

like image 186
yossarian Avatar answered Sep 07 '25 20:09

yossarian


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
like image 37
Pak Uula Avatar answered Sep 07 '25 20:09

Pak Uula