/*
Retrieves all end-entity certificates which satisfy constraints
and requirements specified in the parameters and PKIX state.
423381
private void getMatchingEECerts(ForwardState currentState,
                                    List<CertStore> certStores,
                                    Collection<X509Certificate> eeCerts)
        throws IOException
    {
        if (debug != null) {
            debug.println("ForwardBuilder.getMatchingEECerts()...");
        }
        /*
         * Compose a certificate matching rule to filter out
         * certs which don't satisfy constraints
         *
         * First, retrieve clone of current target cert constraints,
         * and then add more selection criteria based on current validation
         * state. Since selector never changes, cache local copy & reuse.
         */
        if (eeSelector == null) {
            eeSelector = (X509CertSelector) targetCertConstraints.clone();

            /*
             * Match on certificate validity date
             */
            eeSelector.setCertificateValid(buildParams.date());

            /*
             * Policy processing optimizations
             */
            if (buildParams.explicitPolicyRequired()) {
                eeSelector.setPolicy(getMatchingPolicies());
            }
            /*
             * Require EE certs
             */
            eeSelector.setBasicConstraints(-2);
        }

        /* Retrieve matching EE certs from CertStores */
        addMatchingCerts(eeSelector, certStores, eeCerts, searchAllCertStores);
    }
144621
public static PKIXCertPathBuilderResult verifyChain(X509Certificate testCert, X509Certificate... additionalCerts) {
        try {
            // Check for self-signed certificate
            if (isSelfSigned(testCert)) {
                throw new RuntimeException("The certificate is self-signed.  Nothing to verify.");
            }

            // Prepare a set of all certificates
            // chain builder must have all certs, including cert to validate
            // http://stackoverflow.com/a/10788392
            Set<X509Certificate> certs = new HashSet<X509Certificate>();
            certs.add(testCert);
            certs.addAll(Arrays.asList(additionalCerts));

            // Attempt to build the certification chain and verify it
            // Create the selector that specifies the starting certificate
            X509CertSelector selector = new X509CertSelector();
            selector.setCertificate(testCert);

            // Create the trust anchors (set of root CA certificates)
            Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
            for (X509Certificate cert : additionalCerts) {
                if (isSelfSigned(cert)) {
                    trustAnchors.add(new TrustAnchor(cert, null));
                }
            }

            // Configure the PKIX certificate builder
            PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustAnchors, selector);
            pkixParams.setRevocationEnabled(false);
            pkixParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs), BC));

            // Build and verify the certification chain
            CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", BC);
            PKIXCertPathBuilderResult verifiedCertChain = (PKIXCertPathBuilderResult) builder.build(pkixParams);

            // The chain is built and verified
            return verifiedCertChain;
        } catch (CertPathBuilderException e) {
            throw new RuntimeException("Error building certification path: " + testCert.getSubjectX500Principal(), e);
        } catch (Exception e) {
            throw new RuntimeException("Error verifying the certificate: " + testCert.getSubjectX500Principal(), e);
        }
    }
871632
@Override
    public List<Class<? extends AbstractResource>> getEndpoints() {
        List<Class<? extends AbstractResource>> result = new LinkedList<>();

        result.add(AuditResources.class);
        result.add(AuthResources.class);
        result.add(AuthResourcesV2.class);
        result.add(AlertResources.class);
        result.add(AnnotationResources.class);
        result.add(CollectionResources.class);
        result.add(DashboardResources.class);
        result.add(HistoryResources.class);
        result.add(ManagementResources.class);
        result.add(MetricResources.class);
        result.add(NamespaceResources.class);
        result.add(UserResources.class);
        result.add(DiscoveryResources.class);
        return result;
    }
277085
public AuthenticationRequestBuilder getAuthorizationEndPoint() {
    for(Authentication auth : authentications.values()) {
     if (auth instanceof OAuth) {
        OAuth oauth = (OAuth) auth;
        return oauth.getAuthenticationRequestBuilder();
      }
    }
    return null;
  }
753557
private void getMatchingCACerts(ForwardState currentState,
                                    List<CertStore> certStores,
                                    Collection<X509Certificate> caCerts)
        throws IOException
    {
        if (debug != null) {
            debug.println("ForwardBuilder.getMatchingCACerts()...");
        }
        int initialSize = caCerts.size();

        /*
         * Compose a CertSelector to filter out
         * certs which do not satisfy requirements.
         */
        X509CertSelector sel = null;

        if (currentState.isInitial()) {
            if (targetCertConstraints.getBasicConstraints() == -2) {
                // no need to continue: this means we never can match a CA cert
                return;
            }

            /* This means a CA is the target, so match on same stuff as
             * getMatchingEECerts
             */
            if (debug != null) {
                debug.println("ForwardBuilder.getMatchingCACerts(): ca is target");
            }

            if (caTargetSelector == null) {
                caTargetSelector =
                    (X509CertSelector) targetCertConstraints.clone();

                /*
                 * Since we don't check the validity period of trusted
                 * certificates, please don't set the certificate valid
                 * criterion unless the trusted certificate matching is
                 * completed.
                 */

                /*
                 * Policy processing optimizations
                 */
                if (buildParams.explicitPolicyRequired())
                    caTargetSelector.setPolicy(getMatchingPolicies());
            }

            sel = caTargetSelector;
        } else {

            if (caSelector == null) {
                caSelector = new AdaptableX509CertSelector();

                /*
                 * Since we don't check the validity period of trusted
                 * certificates, please don't set the certificate valid
                 * criterion unless the trusted certificate matching is
                 * completed.
                 */

                /*
                 * Policy processing optimizations
                 */
                if (buildParams.explicitPolicyRequired())
                    caSelector.setPolicy(getMatchingPolicies());
            }

            /*
             * Match on subject (issuer of previous cert)
             */
            caSelector.setSubject(currentState.issuerDN);

            /*
             * Match on subjectNamesTraversed (both DNs and AltNames)
             * (checks that current cert's name constraints permit it
             * to certify all the DNs and AltNames that have been traversed)
             */
            CertPathHelper.setPathToNames
                (caSelector, currentState.subjectNamesTraversed);

            /*
             * Facilitate certification path construction with authority
             * key identifier and subject key identifier.
             */
            AuthorityKeyIdentifierExtension akidext =
                    currentState.cert.getAuthorityKeyIdentifierExtension();
            caSelector.parseAuthorityKeyIdentifierExtension(akidext);

            /*
             * check the validity period
             */
            caSelector.setValidityPeriod(currentState.cert.getNotBefore(),
                                         currentState.cert.getNotAfter());

            sel = caSelector;
        }

        /*
         * For compatibility, conservatively, we don't check the path
         * length constraint of trusted anchors.  Please don't set the
         * basic constraints criterion unless the trusted certificate
         * matching is completed.
         */
        sel.setBasicConstraints(-1);

        for (X509Certificate trustedCert : trustedCerts) {
            if (sel.match(trustedCert)) {
                if (debug != null) {
                    debug.println("ForwardBuilder.getMatchingCACerts: "
                        + "found matching trust anchor");
                }
                if (caCerts.add(trustedCert) && !searchAllCertStores) {
                    return;
                }
            }
        }

        /*
         * The trusted certificate matching is completed. We need to match
         * on certificate validity date.
         */
        sel.setCertificateValid(buildParams.date());

        /*
         * Require CA certs with a pathLenConstraint that allows
         * at least as many CA certs that have already been traversed
         */
        sel.setBasicConstraints(currentState.traversedCACerts);

        /*
         * If we have already traversed as many CA certs as the maxPathLength
         * will allow us to, then we don't bother looking through these
         * certificate pairs. If maxPathLength has a value of -1, this
         * means it is unconstrained, so we always look through the
         * certificate pairs.
         */
        if (currentState.isInitial() ||
           (buildParams.maxPathLength() == -1) ||
           (buildParams.maxPathLength() > currentState.traversedCACerts))
        {
            if (addMatchingCerts(sel, certStores,
                                 caCerts, searchAllCertStores)
                && !searchAllCertStores) {
                return;
            }
        }

        if (!currentState.isInitial() && Builder.USE_AIA) {
            // check for AuthorityInformationAccess extension
            AuthorityInfoAccessExtension aiaExt =
                currentState.cert.getAuthorityInfoAccessExtension();
            if (aiaExt != null) {
                getCerts(aiaExt, caCerts);
            }
        }

        if (debug != null) {
            int numCerts = caCerts.size() - initialSize;
            debug.println("ForwardBuilder.getMatchingCACerts: found " +
                numCerts + " CA certs");
        }
    }
186736
public List<EntityType> resolve(Collection<EntityType> entityTypes) {
    if (entityTypes.isEmpty()) {
      return emptyList();
    }
    if (entityTypes.size() == 1) {
      return singletonList(entityTypes.iterator().next());
    }

    // EntityType doesn't have equals/hashcode methods, map to nodes first
    // ensure that nodes exist for all dependencies
    Set<EntityTypeNode> entityTypeNodes =
        entityTypes
            .stream()
            .map(EntityTypeNode::new)
            .flatMap(
                node -> Stream.concat(Stream.of(node), expandEntityTypeDependencies(node).stream()))
            .collect(toCollection(HashSet::new));

    // Sort nodes based on dependencies
    List<EntityTypeNode> resolvedEntityMetaNodes =
        genericDependencyResolver.resolve(entityTypeNodes, getDependencies());
    // Map nodes back to EntityType
    List<EntityType> resolvedEntityMetas =
        resolvedEntityMetaNodes.stream().map(EntityTypeNode::getEntityType).collect(toList());

    // getDependencies might have included items that are not in the input list, remove additional
    // items
    if (resolvedEntityMetas.size() == entityTypes.size()) {
      return resolvedEntityMetas;
    } else {
      Map<String, EntityType> entityTypeMap =
          entityTypes.stream().collect(toMap(EntityType::getId, Function.identity()));
      return resolvedEntityMetas
          .stream()
          .filter(resolvedEntityMeta -> entityTypeMap.containsKey(resolvedEntityMeta.getId()))
          .collect(toList());
    }
  }
466252
synchronized public SSLParameters getSSLParameters() {
        SSLParameters params = super.getSSLParameters();

        // the super implementation does not handle the following parameters
        params.setEndpointIdentificationAlgorithm(identificationProtocol);
        params.setAlgorithmConstraints(algorithmConstraints);

        return params;
    }
80467
private Collection<String> getCertServerNames(X509Certificate x509)
        throws CertificateParsingException {

        Collection<String> serverNames = new LinkedHashSet<>();

        /* Add CN for the certificate */
        String certCN = getCertCN(x509);
        serverNames.add(certCN);

        /* Add alternative names for each certificate */
        try {
            Collection<List<?>> altNames = x509.getSubjectAlternativeNames();
            if (altNames != null) {
                for (List<?> entry : altNames) {
                    if (entry.size() >= 2) {
                        Object entryType = entry.get(0);
                        if (entryType instanceof Integer &&
                            (Integer) entryType == 2) {

                            Object field = entry.get(1);
                            if (field instanceof String) {
                                serverNames.add(((String) field).toLowerCase());
                            }
                        }
                    }
                }
            }

        } catch (CertificateParsingException cpe) {
            LOGGER.warn("Certificate alternative names ignored for certificate " + (certCN != null ? " " + certCN : ""), cpe);
        }

        return serverNames;
    }
243307
@Override
  public ImmutableList<Require> getRequires() {
    if (hasFullParseDependencyInfo) {
      return ImmutableList.copyOf(orderedRequires);
    }

    return getDependencyInfo().getRequires();
  }
538638
public Set<String> getCriticalExtensionOIDs() {
        if (info == null) {
            return null;
        }
        try {
            CertificateExtensions exts = (CertificateExtensions)info.get(
                                         CertificateExtensions.NAME);
            if (exts == null) {
                return null;
            }
            Set<String> extSet = new TreeSet<>();
            for (Extension ex : exts.getAllExtensions()) {
                if (ex.isCritical()) {
                    extSet.add(ex.getExtensionId().toString());
                }
            }
            return extSet;
        } catch (Exception e) {
            return null;
        }
    }
692032
private Set<String> getOcspUrls(Certificate bcCert)
  {
    TBSCertificate bcTbsCert = bcCert.getTBSCertificate();
    Extensions bcExts = bcTbsCert.getExtensions();
    if (bcExts == null)
    {
      throw new RuntimeException("Failed to get Tbs Certificate.");
    }

    Set<String> ocsp = new HashSet<>();
    for (Enumeration en = bcExts.oids(); en.hasMoreElements(); )
    {
      ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) en.nextElement();
      Extension bcExt = bcExts.getExtension(oid);
      if (bcExt.getExtnId() == Extension.authorityInfoAccess)
      {
        // OCSP URLS are included in authorityInfoAccess
        DLSequence seq = (DLSequence) bcExt.getParsedValue();
        for (ASN1Encodable asn : seq)
        {
          ASN1Encodable[] pairOfAsn = ((DLSequence) asn).toArray();
          if (pairOfAsn.length == 2)
          {
            ASN1ObjectIdentifier key = (ASN1ObjectIdentifier) pairOfAsn[0];
            if (key == OIDocsp)
            {
              // ensure OCSP and not CRL
              GeneralName gn = GeneralName.getInstance(pairOfAsn[1]);
              ocsp.add(gn.getName().toString());
            }
          }
        }
      }
    }
    return ocsp;
  }
603358
private X509Certificate[] getPeerCertificates() {
        X509Certificate[] rc = null;
        SSLContext ssl = this.connection.getSSLContext();
        if (null != ssl && (ssl.getNeedClientAuth() || ssl.getWantClientAuth())) {
            try {
                Object[] objs = ssl.getSession().getPeerCertificates();
                if (null != objs) {
                    rc = (X509Certificate[]) objs;
                }
            } catch (Throwable t) {
                FFDCFilter.processException(t,
                                            getClass().getName(), "peercerts",
                                            new Object[] { this, ssl });
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                    Tr.event(tc, "Error getting peer certs; " + t);
                }
            }
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            if (null == rc) {
                Tr.debug(tc, "getPeerCertificates: none");
            } else {
                Tr.debug(tc, "getPeerCertificates: " + rc.length);
            }
        }
        return rc;
    }
303545
public Certificate[] getCertificates() {
        // getCodeSigners() does the sec check
        final CodeSigner[] codeSigners = getCodeSigners();
        if (codeSigners == null) {
            return null;
        }
        final List<Certificate> certList = new ArrayList<Certificate>(codeSigners.length * 3);
        for (CodeSigner signer : codeSigners) {
            certList.addAll(signer.getSignerCertPath().getCertificates());
        }
        return certList.toArray(new Certificate[certList.size()]);
    }
354778
@Override
  public Certificates getAvailableCertificates(Integer pageNo, Integer perPage)
      throws DigitalOceanException, RequestUnsuccessfulException {
    validatePageNo(pageNo);

    return (Certificates) perform(new ApiRequest(ApiAction.AVAILABLE_CERTIFICATES, pageNo, perPage))
        .getData();
  }
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
974768
private Map<String, JsonObject> findCertificateAuthorities() throws NetworkConfigurationException {
        Map<String, JsonObject> ret = new HashMap<>();

        JsonObject jsonCertificateAuthorities = getJsonObject(jsonConfig, "certificateAuthorities");
        if (null != jsonCertificateAuthorities) {

            for (Entry<String, JsonValue> entry : jsonCertificateAuthorities.entrySet()) {
                String name = entry.getKey();

                JsonObject jsonCA = getJsonValueAsObject(entry.getValue());
                if (jsonCA == null) {
                    throw new NetworkConfigurationException(format("Error loading config. Invalid CA entry: %s", name));
                }
                ret.put(name, jsonCA);
            }
        }

        return ret;

    }
807433
public static List<Certificate> loadCertificates(final String certpem) throws IOException,
            CertificateException {
        final StringReader certReader = new StringReader(certpem);
        try (BufferedReader reader = new BufferedReader(certReader)) {
            return loadCertificates(reader);
        }
    }