Convert an X509 certificate into a Python dictionary

    This function converts the given X509 certificate into a Python dictionary
    in the manner established by the Python standard library's ssl module.
977445
def decode_cert(cert):
    

    ret_dict = {}
    subject_xname = X509_get_subject_name(cert.value)
    ret_dict["subject"] = _create_tuple_for_X509_NAME(subject_xname)

    notAfter = X509_get_notAfter(cert.value)
    ret_dict["notAfter"] = ASN1_TIME_print(notAfter)

    peer_alt_names = _get_peer_alt_names(cert)
    if peer_alt_names is not None:
        ret_dict["subjectAltName"] = peer_alt_names

    return ret_dict
684226
def process_pem_cert(self, data, name, idx):
        
        from cryptography.x509.base import load_der_x509_certificate
        try:
            x509 = load_der_x509_certificate(pem_to_der(data), self.get_backend())
            self.num_pem_certs += 1
            return self.process_x509(x509, name=name, idx=idx, data=data, pem=True, source='pem-cert')

        except Exception as e:
            logger.debug('PEM processing failed: %s' % e)
            self.trace_logger.log(e)
690607
def as_dict(self, decode=False):
        
        res = self.database.hgetall(self.key)
        return decode_dict(res) if decode else res
1216598
def dict_to_unicode(raw_dict):
    
    decoded = {}
    for key, value in raw_dict.items():
        decoded[to_unicode(key)] = map(
            to_unicode, value)
    return decoded
449108
def der_cert(der_data):
    
    if isinstance(der_data, str):
        der_data = bytes(der_data, 'utf-8')
    return x509.load_der_x509_certificate(der_data, default_backend())
850220
def get_certificate(self, filename):
        
        cert = self.get_certificate_der(filename)
        certificate = x509.Certificate.load(cert)

        return certificate
1019784
def create_key_pair(self, cert_type, bits):
        

        pkey = crypto.PKey()
        pkey.generate_key(cert_type, bits)
        return pkey
1301455
def certs(self, entity_id, descriptor, use="signing"):
        '''
        
        '''
        ent = self[entity_id]

        def extract_certs(srvs):
            res = []
            for srv in srvs:
                if "key_descriptor" in srv:
                    for key in srv["key_descriptor"]:
                        if "use" in key and key["use"] == use:
                            for dat in key["key_info"]["x509_data"]:
                                cert = repack_cert(
                                    dat["x509_certificate"]["text"])
                                if cert not in res:
                                    res.append(cert)
                        elif not "use" in key:
                            for dat in key["key_info"]["x509_data"]:
                                cert = repack_cert(
                                    dat["x509_certificate"]["text"])
                                if cert not in res:
                                    res.append(cert)

            return res

        if descriptor == "any":
            res = []
            for descr in ["spsso", "idpsso", "role", "authn_authority",
                          "attribute_authority", "pdp"]:
                try:
                    srvs = ent["%s_descriptor" % descr]
                except KeyError:
                    continue

                res.extend(extract_certs(srvs))
        else:
            srvs = ent["%s_descriptor" % descriptor]
            res = extract_certs(srvs)

        return res
651935
def as_dict(self):
        
        d = {"@module": self.__class__.__module__,
             "@class": self.__class__.__name__}
        # print("in as_dict", type(self.x), type(self.c), type(self.xc))
        if self.x is not None: d["x"] = self.x.as_dict()
        if self.c is not None: d["c"] = self.c.as_dict()
        if self.xc is not None: d["xc"] = self.xc.as_dict()
        return d
960648
def matches_hostname(cls, certificate: cryptography.x509.Certificate, hostname: str) -> None:
        
        # Extract the names from the certificate to create the properly-formatted dictionary
        certificate_names = {
            'subject': (tuple([('commonName', name) for name in cls.get_common_names(certificate.subject)]),),
            'subjectAltName': tuple([('DNS', name) for name in cls.get_dns_subject_alternative_names(certificate)]),
        }
        # CertificateError is raised on failure
        ssl.match_hostname(certificate_names, hostname)
116593
def to_dict(dictish):
    
    if hasattr(dictish, 'iterkeys'):
        m = dictish.iterkeys
    elif hasattr(dictish, 'keys'):
        m = dictish.keys
    else:
        raise ValueError(dictish)

    return dict((k, dictish[k]) for k in m())
955030
def to_dict(self):
        
        return dict(
            host=self.host,
            port=self.port,
            database=self.database,
            username=self.username,
            password=self.password,
        )
241596
def cert(self):
        
        if self.cert_files is not None:
            return self.cert_files

        certs = self.certs or '/certs/'
        ssl_path = os.path.join(os.pardir, certs)
        try:
            cert_path = os.listdir(ssl_path)
        except FileNotFoundError:
            raise CertsError(certs)
        except OSError:   # Python 2 compatability
            raise CertsError(certs)

        cert = None
        key = None
        for file in cert_path:
            ext = os.path.splitext(file)[-1]
            if ext in ['.crt', '.cert']:
                cert = os.path.join(ssl_path, file)
            elif ext == '.key':
                key = os.path.join(ssl_path, file)
        if cert is None or key is None:
            raise CertsError(certs)
        return [cert, key]
520074
def load_pkcs12(self, key):
        
        self.x509 = key.get_certificate().to_cryptography()
        self.public_key = key.get_certificate().to_cryptography().public_key()
        self.private_key = key.get_privatekey().to_cryptography_key()
563396
def to_dict(self):
        
        return dict(
            addr=self.addr,
            protocol=self.protocol,
            weight=self.weight,
            last_checked=self.last_checked)
1074176
def generate_certificate_pure_python(common_name, size=DEFAULT_KEY_SIZE,
                                        digest=DEFAULT_DIGEST):
    '''
        
    '''
    private_key = OpenSSL.crypto.PKey()
    private_key.generate_key(TYPE_RSA, size)

    request = OpenSSL.crypto.X509Req()
    subject = request.get_subject()
    setattr(subject, 'CN', common_name)
    request.set_pubkey(private_key)
    request.sign(private_key, digest)

    certificate = OpenSSL.crypto.X509()
    certificate.set_serial_number(0)
    certificate.gmtime_adj_notBefore(0)
    certificate.gmtime_adj_notAfter(60 * 60 * 24 * 365 * 5)
    certificate.set_issuer(request.get_subject())
    certificate.set_subject(request.get_subject())
    certificate.set_pubkey(request.get_pubkey())
    certificate.sign(private_key, digest)

    private_key_path = '{}/{}.key'.format(CERTIFICATES_PATH, common_name)
    if not os.path.isfile(private_key_path):
        print 'Write {}'.format(private_key_path)
        with open(private_key_path, 'w+') as private_key_file:
            private_key_file.write(
                OpenSSL.crypto.dump_privatekey(FILETYPE_PEM,
                                               private_key).decode('utf-8')
            )
        helpers.file_rights(private_key_path, mode=0400, uid=0, gid=0)
    else:
        print 'Already exist: {}'.format(private_key_path)

    certificate_path = '{}/{}.crt'.format(CERTIFICATES_PATH, common_name)
    if not os.path.isfile(certificate_path):
        print 'Write {}'.format(certificate_path)
        with open(certificate_path, 'w+') as certificate_file:
            certificate_file.write(
                OpenSSL.crypto.dump_certificate(FILETYPE_PEM,
                                                certificate).decode('utf-8')
            )
        helpers.file_rights(certificate_path, mode=0444, uid=0, gid=0)
    else:
        print 'Already exist: {}'.format(certificate_path)

    clean_links()
    make_links(common_name)
150147
def to_dict(self):
        
        if self.id:
            return {"id": self.id}
        return {"type": self.type, "ipVersion": self.ip_version}