def get_pkcs7_certificates(bundle): """ Extracts X.509 certificates from an OpenSSL PKCS7 object. Args: bundle (OpenSSL PKCS7 object) : PKCS7 object to extract the certificates from. Returns: A tuple containing the extracted certificates (cryptography X.509 certificates, not OpenSSL X.509 certificates!) """ from OpenSSL._util import (ffi as _ffi, lib as _lib) from OpenSSL.crypto import X509 pkcs7_certs = _ffi.NULL if bundle.type_is_signed(): pkcs7_certs = bundle._pkcs7.d.sign.cert elif bundle.type_is_signedAndEnveloped(): pkcs7_certs = bundle._pkcs7.d.signed_and_enveloped.cert certificates = [] for i in range(_lib.sk_X509_num(pkcs7_certs)): certificate = X509.__new__(X509) certificate._x509 = _ffi.gc( _lib.X509_dup(_lib.sk_X509_value(pkcs7_certs, i)), _lib.X509_free) certificates.append(certificate.to_cryptography()) if not certificates: return tuple() return tuple(certificates)
def get_certificates(self): from OpenSSL.crypto import X509 from OpenSSL._util import ffi as _ffi, lib as _lib certs = _ffi.NULL if self.type_is_signed(): certs = self._pkcs7.d.sign.cert elif self.type_is_signedAndEnveloped(): certs = self._pkcs7.d.signed_and_enveloped.cert pycerts = [] for i in range(_lib.sk_X509_num(certs)): pycert = X509.__new__(X509) pycert._x509 = _lib.sk_X509_value(certs, i) pycerts.append(pycert) if not pycerts: return None return tuple(pycerts)
def get_peer_cert_chain(self): """ Retrieve the other side's certificate (if any) :return: A list of X509 instances giving the peer's certificate chain, or None if it does not have one. """ cert_stack = _lib.SSL_get_peer_cert_chain(self._ssl) if cert_stack == _ffi.NULL: return None result = [] for i in range(_lib.sk_X509_num(cert_stack)): # TODO could incref instead of dup here cert = _lib.X509_dup(_lib.sk_X509_value(cert_stack, i)) pycert = X509.__new__(X509) pycert._x509 = _ffi.gc(cert, _lib.X509_free) result.append(pycert) return result
def load_certificates_from_signature(signature): signature = base64.b64decode(signature) pkcs7 = crypto.load_pkcs7_data(crypto.FILETYPE_ASN1, signature) raw_certificates = ffi.NULL if pkcs7.type_is_signed(): raw_certificates = pkcs7._pkcs7.d.sign.cert elif pkcs7.type_is_signedAndEnveloped(): raw_certificates = pkcs7._pkcs7.d.signed_and_enveloped.cert certificates = [] for x in range(lib.sk_X509_num(raw_certificates)): certificate = lib.X509_dup(lib.sk_X509_value(raw_certificates, x)) certificate = crypto.X509._from_raw_x509_ptr(certificate) certificate = ApplePieCertificate(certificate) certificates.append(certificate) return certificates