Returns the certificate matching the TLSA record from the given certs

@param tlsaRecord TLSARecord type describing the TLSA Record to be validated
@param certs All certs retrieved from the URL's SSL/TLS connection
@return Matching certificate or null
963858
public Certificate getMatchingCert(TLSARecord tlsaRecord, List<Certificate> certs) {

        for (Certificate cert : certs) {

            byte[] digestMatch = new byte[0];
            byte[] selectorData = new byte[0];

            try {
                // Get Selector Value
                switch (tlsaRecord.getSelector()) {
                    case TLSARecord.Selector.FULL_CERTIFICATE:
                        selectorData = cert.getEncoded();
                        break;

                    case TLSARecord.Selector.SUBJECT_PUBLIC_KEY_INFO:
                        selectorData = cert.getPublicKey().getEncoded();
                        break;
                }

                // Validate Matching Type
                switch (tlsaRecord.getMatchingType()) {
                    case TLSARecord.MatchingType.EXACT:
                        digestMatch = selectorData;
                        break;
                    case TLSARecord.MatchingType.SHA256:
                        digestMatch = MessageDigest.getInstance("SHA-256").digest(selectorData);
                        break;
                    case TLSARecord.MatchingType.SHA512:
                        digestMatch = MessageDigest.getInstance("SHA-512").digest(selectorData);
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (Arrays.equals(digestMatch, tlsaRecord.getCertificateAssociationData())) {
                return cert;
            }
        }

        return null;
    }
925790
public static CERTRecord
buildRecord(Name name, int dclass, long ttl, Certificate cert, int tag,
	    int alg)
{
	int type;
	byte [] data;

	try {
		if (cert instanceof X509Certificate) {
			type = CERTRecord.PKIX;
			data = cert.getEncoded();
		}
		else
			return null;

		return new CERTRecord(name, dclass, ttl, type, tag, alg, data);
	}
	catch (CertificateException e) {
		if (Options.check("verboseexceptions"))
			System.err.println("Cert build exception:" + e);
		return null;
	}
}
1313477
public Certificate findCertificateById(byte[] certificateId) throws CertificateNotFoundException {
        if (certificateId == null) {
            throw new CertificateNotFoundException("Certificate with id null not found from pubFile='" + this.toString() + "'");
        }
        for (InMemoryCertificateRecord record : certificateRecords) {
            if (Arrays.equals(certificateId, record.getCertificateId())) {
                return X509CertUtil.toCert(record.getCertificate());
            }
        }
        throw new CertificateNotFoundException("Certificate with id " + Base64.encode(certificateId) + " not found from pubFile='" + this.toString() + "'");
    }
880648
public List<Certificate> getUrlCerts(URL url) {

        SSLSocket socket = null;

        TrustManager trm = new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        };

        try {

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{trm}, null);
            SSLSocketFactory factory = sc.getSocketFactory();
            socket = (SSLSocket) factory.createSocket(url.getHost(), (url.getPort() == -1) ? url.getDefaultPort() : url.getPort());
            socket.startHandshake();
            SSLSession session = socket.getSession();
            Certificate[] certArray = session.getPeerCertificates();
            return new ArrayList<Certificate>(Arrays.asList(certArray));

        } catch (Exception e){
            e.printStackTrace();
        } finally {
            if (socket != null && socket.isConnected()) {
                try {
                    socket.close();
                } catch (IOException ignored) {}
            }
        }

        return new ArrayList<Certificate>();
    }
980451
public static sslcertkey_sslocspresponder_binding[] get_filtered(nitro_service service, String certkey, String filter) throws Exception{
		sslcertkey_sslocspresponder_binding obj = new sslcertkey_sslocspresponder_binding();
		obj.set_certkey(certkey);
		options option = new options();
		option.set_filter(filter);
		sslcertkey_sslocspresponder_binding[] response = (sslcertkey_sslocspresponder_binding[]) obj.getfiltered(service, option);
		return response;
	}
83656
private X509Certificate getClientCert(HttpsExchange pHttpsExchange) {
        try {
            Certificate[] peerCerts = pHttpsExchange.getSSLSession().getPeerCertificates();
            return peerCerts != null && peerCerts.length > 0 ? (X509Certificate) peerCerts[0] : null;
        } catch (SSLPeerUnverifiedException e) {
            throw new SecurityException("SSL Peer couldn't be verified");
        }

    }
124801
public static byte[] getEncodedInternal(Certificate cert)
            throws CertificateEncodingException {
        if (cert instanceof X509CertImpl) {
            return ((X509CertImpl)cert).getEncodedInternal();
        } else {
            return cert.getEncoded();
        }
    }
903468
private String getCerticateSubject(AtomicServiceReference<Object> serviceRef, Properties sslProperties) {
        String certificateDN = null;
        try {
            certificateDN = sslHelper.getClientKeyCertSubject(serviceRef, sslProperties);
        } catch (KeyStoreException ke) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.error(tc, "CWKKD0020.ssl.get.certificate.user", MONGO, id, ke);
            }
            throw new RuntimeException(Tr.formatMessage(tc, "CWKKD0020.ssl.get.certificate.user", MONGO, id, ke));
        } catch (CertificateException ce) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.error(tc, "CWKKD0020.ssl.get.certificate.user", MONGO, id, ce);
            }
            throw new RuntimeException(Tr.formatMessage(tc, "CWKKD0020.ssl.get.certificate.user", MONGO, id, ce));
        }

        // handle null .... cannot find the client key
        if (certificateDN == null) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.error(tc, "CWKKD0026.ssl.certificate.exception", MONGO, id);
            }
            throw new RuntimeException(Tr.formatMessage(tc, "CWKKD0026.ssl.certificate.exception", MONGO, id));
        }

        return certificateDN;
    }
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");
        }
    }
994079
public static String getIssuedTo(final X509Certificate certificate)
	{
		final X500Principal issuedToPrincipal = certificate.getIssuerX500Principal();
		final String issuedTo = issuedToPrincipal.getName();
		return issuedTo;
	}
212793
public CertifiedPublicKey convert(X509CertificateHolder cert)
    {
        if (cert == null) {
            return null;
        }
        return new BcX509CertifiedPublicKey(cert, this.factory);
    }
613674
def ClientCertFromCSR(cls, csr):
    
    builder = x509.CertificateBuilder()
    # Use the client CN for a cert serial_id. This will ensure we do
    # not have clashing cert id.
    common_name = csr.GetCN()
    serial = int(common_name.split(".")[1], 16)
    builder = builder.serial_number(serial)
    builder = builder.subject_name(
        x509.Name(
            [x509.NameAttribute(oid.NameOID.COMMON_NAME, str(common_name))]))

    now = rdfvalue.RDFDatetime.Now()
    now_plus_year = now + rdfvalue.Duration("52w")
    builder = builder.not_valid_after(now_plus_year.AsDatetime())
    now_minus_ten = now - rdfvalue.Duration("10s")
    builder = builder.not_valid_before(now_minus_ten.AsDatetime())
    # TODO(user): dependency loop with
    # grr/core/grr_response_core/config/client.py.
    # pylint: disable=protected-access
    ca_cert = config_lib._CONFIG["CA.certificate"]
    # pylint: enable=protected-access
    builder = builder.issuer_name(ca_cert.GetIssuer())
    builder = builder.public_key(csr.GetPublicKey().GetRawPublicKey())

    # TODO(user): dependency loop with
    # grr/core/grr_response_core/config/client.py.
    # pylint: disable=protected-access
    ca_key = config_lib._CONFIG["PrivateKeys.ca_key"]
    # pylint: enable=protected-access

    return RDFX509Cert(
        builder.sign(
            private_key=ca_key.GetRawPrivateKey(),
            algorithm=hashes.SHA256(),
            backend=openssl.backend))
565998
def query_certificate(self, cert_hash):
        
        try:
            cquery = self.pssl.query_cert(cert_hash)
        except Exception:
            self.error('Exception during processing with passiveSSL. '
                       'This happens if the given hash is not sha1 or contains dashes/colons etc. '
                       'Please make sure to submit a clean formatted sha1 hash.')

        # fetch_cert raises an error if no certificate was found.
        try:
            cfetch = self.pssl.fetch_cert(cert_hash, make_datetime=False)
        except Exception:
            cfetch = {}

        return {'query': cquery,
                'cert': cfetch}
411590
def get_certificate_der(self, filename):
        
        pkcs7message = self.get_file(filename)

        pkcs7obj = cms.ContentInfo.load(pkcs7message)
        cert = pkcs7obj['content']['certificates'][0].chosen.dump()
        return cert
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);
    }
1122299
@Override
  public X509Certificate getClientCertificate()
    throws CertificateException
  {
    X509Certificate []certs = getClientCertificates();

    if (certs == null || certs.length == 0)
      return null;
    else
      return certs[0];
  }
157225
function(cert) {
      var sAttr = cert.issuer.attributes;

      for(var i = 0; i < msg.recipients.length; ++i) {
        var r = msg.recipients[i];
        var rAttr = r.issuer;

        if(r.serialNumber !== cert.serialNumber) {
          continue;
        }

        if(rAttr.length !== sAttr.length) {
          continue;
        }

        var match = true;
        for(var j = 0; j < sAttr.length; ++j) {
          if(rAttr[j].type !== sAttr[j].type ||
            rAttr[j].value !== sAttr[j].value) {
            match = false;
            break;
          }
        }

        if(match) {
          return r;
        }
      }

      return null;
    }