Get certs from cache if present; otherwise, gets from URI and caches them.

  Args:
    cert_uri: URI from which to retrieve certs if cache is stale or empty.
    cache: Cache of pre-fetched certs.

  Returns:
    The retrieved certs.
423114
def _get_cached_certs(cert_uri, cache):
  
  certs = cache.get(cert_uri, namespace=_CERT_NAMESPACE)
  if certs is None:
    _logger.debug('Cert cache miss for %s', cert_uri)
    try:
      result = urlfetch.fetch(cert_uri)
    except AssertionError:
      # This happens in unit tests.  Act as if we couldn't get any certs.
      return None

    if result.status_code == 200:
      certs = json.loads(result.content)
      expiration_time_seconds = _get_cert_expiration_time(result.headers)
      if expiration_time_seconds:
        cache.set(cert_uri, certs, time=expiration_time_seconds,
                  namespace=_CERT_NAMESPACE)
    else:
      _logger.error(
          'Certs not available, HTTP request returned %d', result.status_code)

  return certs
672684
def get_certificate(self, certificate_uid):
        
        logging.debug('Retrieving certificate for uid=%s', certificate_uid)

        is_v1_uid = model.is_v1_uid(certificate_uid)
        if not is_v1_uid:
            return super(V1AwareCertificateStore, self).get_certificate(certificate_uid)

        # else it's V1.1 (if not valid, it will throw)
        certificate = self._find_certificate_metadata(uid=certificate_uid)
        if certificate:
            certificate_bytes = self._get_certificate_raw(certificate_uid)
            certificate_json = helpers.certificate_bytes_to_json(certificate_bytes)
            return model.to_certificate_model(certificate_json, certificate['txid'], certificate_bytes)

        message = 'Certificate metadata not found for certificate uid=%s' % certificate_uid
        logging.error(message)
        raise KeyError(message)
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
120349
def get_leaf_certificates(certs):
    
    issuers = [cert.issuer.get_attributes_for_oid(x509.NameOID.COMMON_NAME)
               for cert in certs]
    leafs = [cert for cert in certs
             if (cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME)
                 not in issuers)]
    return leafs
157581
def _get_certificate_raw(self, certificate_uid):
        
        cert_file_bytes = self.kv_store.get(certificate_uid_to_filename(certificate_uid))
        return cert_file_bytes
381379
def load_cert_chain(chain_file):
    
    if hasattr(chain_file, 'read'):
        cert_chain = chain_file.read() 
    else:
        with open(chain_file, 'rb') as f:
            cert_chain = f.read()       
    
    if not cert_chain:
        raise ValueError('Certificate chain file is empty!')

    cert_type_matches = []
    for match in _PEM_RE.finditer(cert_chain):
        cert_type_matches.append((match.group(1), match.group(0)))
    
    if not cert_type_matches:
        raise ValueError('No certificate types were found. Valid types '
            'are: {}'.format(CERT_TYPES))

    return cert_type_matches
349668
public static RevocationStatus check(X509Certificate cert,
                                         X509Certificate issuerCert,
                                         URI responderURI,
                                         X509Certificate responderCert,
                                         Date date, List<Extension> extensions)
        throws IOException, CertPathValidatorException
    {
        CertId certId = null;
        try {
            X509CertImpl certImpl = X509CertImpl.toImpl(cert);
            certId = new CertId(issuerCert, certImpl.getSerialNumberObject());
        } catch (CertificateException | IOException e) {
            throw new CertPathValidatorException
                ("Exception while encoding OCSPRequest", e);
        }
        OCSPResponse ocspResponse = check(Collections.singletonList(certId),
            responderURI, issuerCert, responderCert, date, extensions);
        return (RevocationStatus) ocspResponse.getSingleResponse(certId);
    }
346344
def get(self, uri):
        
        uri = self.URI + uri
        return self._client.get(uri)
741208
def certificates
      return Hash[self.signs.map{|path, sign| [path, sign.certificates.first] }]
    end
550248
def _parse_certificate(cls, response):
        
        links = _parse_header_links(response)
        try:
            cert_chain_uri = links[u'up'][u'url']
        except KeyError:
            cert_chain_uri = None
        return (
            response.content()
            .addCallback(
                lambda body: messages.CertificateResource(
                    uri=cls._maybe_location(response),
                    cert_chain_uri=cert_chain_uri,
                    body=body))
            )
896360
def get(self, uri, params={}):
        '''
        '''
        return self._session.get(urljoin(Investigate.BASE_URL, uri),
            params=params, headers=self._auth_header, proxies=self.proxies
        )
385713
def lookup_cert(self, key):
        
        if not self.consumers:
            log.critical(("No consumers defined in settings."
                          "Have you created a configuration file?"))
            return None

        consumer = self.consumers.get(key)
        if not consumer:
            log.info("Did not find consumer, using key: %s ", key)
            return None
        cert = consumer.get('cert', None)
        return cert
110375
def get_requests_for_local_unit(relation_name=None):
    
    local_name = local_unit().replace('/', '_')
    raw_certs_key = '{}.processed_requests'.format(local_name)
    relation_name = relation_name or 'certificates'
    bundles = []
    for rid in relation_ids(relation_name):
        for unit in related_units(rid):
            data = relation_get(rid=rid, unit=unit)
            if data.get(raw_certs_key):
                bundles.append({
                    'ca': data['ca'],
                    'chain': data.get('chain'),
                    'certs': json.loads(data[raw_certs_key])})
    return bundles
335544
def get_certificate():
    '''  '''
    if os.path.exists(CERT_PATH):
        log('Reading ovs certificate from {}'.format(CERT_PATH))
        with open(CERT_PATH, 'r') as cert:
            full_cert = cert.read()
            begin_marker = "-----BEGIN CERTIFICATE-----"
            end_marker = "-----END CERTIFICATE-----"
            begin_index = full_cert.find(begin_marker)
            end_index = full_cert.rfind(end_marker)
            if end_index == -1 or begin_index == -1:
                raise RuntimeError("Certificate does not contain valid begin"
                                   " and end markers.")
            full_cert = full_cert[begin_index:(end_index + len(end_marker))]
            return full_cert
    else:
        log('Certificate not found', level=WARNING)
        return None
769138
def from_instance(instance, default_ca_certs=None):
    
    method = instance.get('method', 'get')
    data = instance.get('data', {})
    tags = instance.get('tags', [])
    ntlm_domain = instance.get('ntlm_domain')
    username = instance.get('username')
    password = instance.get('password')
    client_cert = instance.get('client_cert')
    client_key = instance.get('client_key')
    http_response_status_code = str(instance.get('http_response_status_code', DEFAULT_EXPECTED_CODE))
    timeout = int(instance.get('timeout', 10))
    config_headers = instance.get('headers', {})
    default_headers = is_affirmative(instance.get("include_default_headers", True))
    if default_headers:
        headers = agent_headers({})
    else:
        headers = {}
    headers.update(config_headers)
    url = instance.get('url')
    if url is not None:
        url = ensure_unicode(url)
    content_match = instance.get('content_match')
    if content_match is not None:
        content_match = ensure_unicode(content_match)
    reverse_content_match = is_affirmative(instance.get('reverse_content_match', False))
    response_time = is_affirmative(instance.get('collect_response_time', True))
    if not url:
        raise ConfigurationError("Bad configuration. You must specify a url")
    if not url.startswith("http"):
        raise ConfigurationError("The url {} must start with the scheme http or https".format(url))
    include_content = is_affirmative(instance.get('include_content', False))
    disable_ssl_validation = is_affirmative(instance.get('disable_ssl_validation', True))
    ssl_expire = is_affirmative(instance.get('check_certificate_expiration', True))
    instance_ca_certs = instance.get('ca_certs', default_ca_certs)
    weakcipher = is_affirmative(instance.get('weakciphers', False))
    ignore_ssl_warning = is_affirmative(instance.get('ignore_ssl_warning', False))
    check_hostname = is_affirmative(instance.get('check_hostname', True))
    skip_proxy = is_affirmative(instance.get('skip_proxy', instance.get('no_proxy', False)))
    allow_redirects = is_affirmative(instance.get('allow_redirects', True))
    stream = is_affirmative(instance.get('stream', False))

    return Config(
        url,
        ntlm_domain,
        username,
        password,
        client_cert,
        client_key,
        method,
        data,
        http_response_status_code,
        timeout,
        include_content,
        headers,
        response_time,
        content_match,
        reverse_content_match,
        tags,
        disable_ssl_validation,
        ssl_expire,
        instance_ca_certs,
        weakcipher,
        check_hostname,
        ignore_ssl_warning,
        skip_proxy,
        allow_redirects,
        stream,
    )
353914
def get_cert_file():
    
    try:
        current_path = os.path.realpath(__file__)
        ca_cert_path = os.path.join(current_path, "..", "..", "..",
                                    "conf", "cacert.pem")
        return os.path.abspath(ca_cert_path)
    except Exception:
        return None
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;
    }