Identifies, decrypts and returns list of cryptography x509 certificates.
338251
def parse_certificates(data, password):
    

    # PEM
    if is_pem(data):
        certs = []
        for cert in data.split(PEM_IDENTIFIER):
            try:
                certs.append(
                    x509.load_pem_x509_certificate(
                        PEM_IDENTIFIER + cert, default_backend()))
            except Exception:
                pass
        # Could be valid PEM but not certificates.
        if len(certs) > 0:
            return certs

    # PKCS12
    if is_pkcs12(data):
        try:
            p12 = crypto.load_pkcs12(data, password)
            data = crypto.dump_certificate(
                crypto.FILETYPE_PEM, p12.get_certificate())
            return [x509.load_pem_x509_certificate(data, default_backend())]
        except crypto.Error as e:
            raise ValueError(e)

    # DER
    try:
        return [x509.load_der_x509_certificate(data, default_backend())]
    except Exception:
        pass

    raise ValueError('Could not parse certificate.')
530844
public X509Certificate[] getAcceptedIssuers() {
        try {
            Collection<X509Certificate> trusted = CertificateLoadUtil.getTrustedCertificates(
                    this.parameters.getTrustStore(), null);
            return trusted.toArray(new X509Certificate[trusted.size()]);
        } catch (KeyStoreException e) {
            logger.warn("Unable to load trusted Certificates.  Authentication will fail.",e);
            return new X509Certificate[]{};
        }
    }
1175085
private Collection<? extends java.security.cert.Certificate>
        parseX509orPKCS7Cert(InputStream is)
        throws CertificateException, IOException
    {
        Collection<X509CertImpl> coll = new ArrayList<>();
        byte[] data = readOneBlock(is);
        if (data == null) {
            return new ArrayList<>(0);
        }
        try {
            PKCS7 pkcs7 = new PKCS7(data);
            X509Certificate[] certs = pkcs7.getCertificates();
            // certs are optional in PKCS #7
            if (certs != null) {
                return Arrays.asList(certs);
            } else {
                // no crls provided
                return new ArrayList<>(0);
            }
        } catch (ParsingException e) {
            while (data != null) {
                coll.add(new X509CertImpl(data));
                data = readOneBlock(is);
            }
        }
        return coll;
    }
395874
private List<String> getCrlDistributionPoints(X509Certificate cert) throws CertificateVerificationException {

        //Gets the DER-encoded OCTET string for the extension value for CRLDistributionPoints.
        byte[] crlDPExtensionValue = cert.getExtensionValue(Extension.cRLDistributionPoints.getId());
        if (crlDPExtensionValue == null) {
            throw new CertificateVerificationException("Certificate doesn't have CRL distribution points");
        }
        //crlDPExtensionValue is encoded in ASN.1 format.
        ASN1InputStream asn1In = new ASN1InputStream(crlDPExtensionValue);
        //DER (Distinguished Encoding Rules) is one of ASN.1 encoding rules defined in ITU-T X.690, 2002, specification.
        //ASN.1 encoding rules can be used to encode any data object into a binary file. Read the object in octets.
        CRLDistPoint distPoint;
        try {
            DEROctetString crlDEROctetString = (DEROctetString) asn1In.readObject();
            //Get Input stream in octets.
            distPoint = getOctetInputStream(crlDEROctetString);
        } catch (IOException e) {
            throw new CertificateVerificationException("Cannot read certificate to get CRL URLs", e);
        } finally {
            try {
                asn1In.close();
            } catch (IOException e) {
                LOG.error("Cannot close input stream", e);
            }
        }

        List<String> crlUrls = new ArrayList<>();
        //Loop through ASN1Encodable DistributionPoints.
        for (DistributionPoint dp : distPoint.getDistributionPoints()) {
            //get ASN1Encodable DistributionPointName.
            DistributionPointName dpn = dp.getDistributionPoint();
            if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) {
                //Create ASN1Encodable General Names.
                GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames();
                // Look for a URI
                for (GeneralName genName : genNames) {
                    if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) {
                        //DERIA5String contains an ascii string.
                        //A IA5String is a restricted character string type in the ASN.1 notation.
                        String url = DERIA5String.getInstance(genName.getName()).getString().trim();
                        crlUrls.add(url);
                    }
                }
            }
        }

        if (crlUrls.isEmpty()) {
            throw new CertificateVerificationException("Cant get CRL urls from certificate");
        }
        return crlUrls;
    }
442067
def get_certificates(self):
        """"""
        for certificate in self.user_data.certificates:
            certificate['datetime'] = certificate['datetime'].strip()

        return self.user_data.certificates
1121234
def _get_certificate_obj(cert):
    '''
    
    '''
    if isinstance(cert, M2Crypto.X509.X509):
        return cert

    text = _text_or_file(cert)
    text = get_pem_entry(text, pem_type='CERTIFICATE')
    return M2Crypto.X509.load_cert_string(text)
1088392
def cert_from_instance(instance):
    
    if instance.signature:
        if instance.signature.key_info:
            return cert_from_key_info(instance.signature.key_info,
                                      ignore_age=True)
    return []
976293
def checksum_chain(self):
        

        checksums = []
        for certificate in self.certificates:
            checksums.append(certificate.checksum)

        return "::".join(checksums)
754374
public static function loadKeyFromX509Resource($res): array
    {
        $key = \openssl_get_publickey($res);

        $details = \openssl_pkey_get_details($key);
        if (isset($details['key'])) {
            $values = self::loadKeyFromPEM($details['key']);
            \openssl_x509_export($res, $out);
            $x5c = \preg_replace('#-.*-#', '', $out);
            $x5c = \preg_replace('~\R~', PHP_EOL, $x5c);
            $x5c = \trim($x5c);
            $values['x5c'] = [$x5c];

            $values['x5t'] = Base64Url::encode(\openssl_x509_fingerprint($res, 'sha1', true));
            $values['x5t#256'] = Base64Url::encode(\openssl_x509_fingerprint($res, 'sha256', true));

            return $values;
        }

        throw new \InvalidArgumentException('Unable to load the certificate');
    }
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
30868
def list_certificates(self):

        '''
            
        '''

        title = '%s.list_certificates' % self.__class__.__name__

    # send request for list of certificates
        self.printer('Querying AWS for server certificates.')
        try:
            response = self.connection.list_server_certificates()
        except:
            raise AWSConnectionError(title)

    # construct certificate list from response
        cert_list = []
        if 'ServerCertificateMetadataList' in response.keys():
            for certificate in response['ServerCertificateMetadataList']:
                cert_list.append(certificate['ServerCertificateName'])

    # report results and return list
        if cert_list:
            print_out = 'Found server certificate'
            if len(cert_list) > 1:
                print_out += 's'
            from labpack.parsing.grammar import join_words
            print_out += ' %s.' % join_words(cert_list)
            self.printer(print_out)
        else:
            self.printer('No server certificates found.')

        self.certificate_list = cert_list
        
        return self.certificate_list
1182229
private X509Certificate getX509Certificate(byte[] pemCertificate) throws CryptoException {
        X509Certificate ret = null;
        CryptoException rete = null;

        List<Provider> providerList = new LinkedList<>(Arrays.asList(Security.getProviders()));
        if (SECURITY_PROVIDER != null) { //Add if overridden
            providerList.add(SECURITY_PROVIDER);
        }
        try {
            providerList.add(BouncyCastleProvider.class.newInstance()); // bouncy castle is there always.
        } catch (Exception e) {
            logger.warn(e);

        }
        for (Provider provider : providerList) {
            try {
                if (null == provider) {
                    continue;
                }
                CertificateFactory certFactory = CertificateFactory.getInstance(CERTIFICATE_FORMAT, provider);
                if (null != certFactory) {
                    try (ByteArrayInputStream bis = new ByteArrayInputStream(pemCertificate)) {
                        Certificate certificate = certFactory.generateCertificate(bis);

                        if (certificate instanceof X509Certificate) {
                            ret = (X509Certificate) certificate;
                            rete = null;
                            break;
                        }
                    }

                }
            } catch (Exception e) {

                rete = new CryptoException(e.getMessage(), e);

            }

        }

        if (null != rete) {

            throw rete;

        }

        if (ret == null) {

            logger.error("Could not convert pem bytes");

        }

        return ret;

    }
1159767
def encrypters(self):
        """"""
        return set(m.encrypter for m in self._sessionkeys if isinstance(m, PKESessionKey))
1122299
@Override
  public X509Certificate getClientCertificate()
    throws CertificateException
  {
    X509Certificate []certs = getClientCertificates();

    if (certs == null || certs.length == 0)
      return null;
    else
      return certs[0];
  }
801979
def getCaCerts(self):
        '''
        
        '''
        retn = []

        path = s_common.genpath(self.certdir, 'cas')

        for name in os.listdir(path):
            if not name.endswith('.crt'):
                continue

            full = s_common.genpath(self.certdir, 'cas', name)
            retn.append(self._loadCertPath(full))

        return retn
220674
protected List<CertificateChecker> getCertificateCheckers() {
        List<CertificateChecker> checkers = new ArrayList<CertificateChecker>();
        checkers.add(new DateValidityChecker());
        checkers.add(new UnsupportedCriticalExtensionChecker());
        checkers.add(new IdentityChecker(this));
        // NOTE: the (possible) refresh of the CRLs happens when we call getDefault.
        // Hence, we must recreate crlsList for each call to checkCertificate
        // Sadly, this also means that the amount of work necessary for checkCertificate
        // can be arbitrarily large (if the CRL is indeed refreshed).
        //
        // Note we DO NOT use this.certStore by default!  TODO: This differs from the unit test
        CertificateRevocationLists crlsList = CertificateRevocationLists.getDefaultCertificateRevocationLists();
        checkers.add(new CRLChecker(crlsList, this.keyStore, true));
        checkers.add(new SigningPolicyChecker(this.policyStore));
        return checkers;
    }
1315332
def cipherprefs(self):
        
        if 'PreferredSymmetricAlgorithms' in self._signature.subpackets:
            return next(iter(self._signature.subpackets['h_PreferredSymmetricAlgorithms'])).flags
        return []