Search all SSL certificate orders.
960016
def search_order(self, limit=100, offset=0, common_name_pattern=None, status=None,
                     contact_handle=None):
        """"""

        response = self.request(E.searchOrderSslCertRequest(
            E.limit(limit),
            E.offset(offset),
            OE('commonNamePattern', common_name_pattern),
            OE('status', status, transform=_simple_array),
            OE('contactHandle', contact_handle),
        ))

        return response.as_models(SSLOrder)
146650
def search(self, read_cache=True, ssl_verify=True, recid=None, **kwparams):
        
        parse_results = False
        of = kwparams.get('of', "")
        if of == "":
            parse_results = True
            of = "xm"
            kwparams['of'] = of
        params = kwparams
        cache_key = (json.dumps(params), parse_results)

        if cache_key not in self.cached_queries or \
                not read_cache:
            if recid:
                results = requests.get(self.server_url + '/record/' + recid,
                                       params=params, cookies=self.cookies,
                                       stream=True, verify=ssl_verify,
                                       allow_redirects=True)
                if results.history:
                    new_recid = urlparse(results.url).path.split('/')[-1]
                    raise InvenioConnectorServerError('The record has been'
                                                      'merged with recid ' +
                                                      new_recid)
            else:
                results = requests.get(self.server_url + "/search",
                                       params=params, cookies=self.cookies,
                                       stream=True, verify=ssl_verify)
            if 'youraccount/login' in results.url:
                # Current user not able to search collection
                raise InvenioConnectorAuthError(
                    "You are trying to search a restricted collection. "
                    "Please authenticate yourself.\n")
        else:
            return self.cached_queries[cache_key]

        if parse_results:
            # FIXME: we should not try to parse if results is string
            parsed_records = self._parse_results(results.raw,
                                                 self.cached_records)
            self.cached_queries[cache_key] = parsed_records
            return parsed_records
        else:
            # pylint: disable=E1103
            # The whole point of the following code is to make sure we can
            # handle two types of variable.
            try:
                res = results.content
            except AttributeError:
                res = results
            # pylint: enable=E1103

            if of == "id":
                try:
                    if isinstance(res, binary_type):
                        # Transform to list
                        res = [int(recid.strip()) for record_id in
                               res.decode('utf-8').strip("[]").split(",")
                               if record_id.strip() != ""]
                    res.reverse()
                except (ValueError, AttributeError):
                    res = []
            self.cached_queries[cache_key] = res
            return res
498290
def load_ssl_context(cert_file, pkey_file):
    """"""
    from OpenSSL import SSL
    ctx = SSL.Context(SSL.SSLv23_METHOD)
    ctx.use_certificate_file(cert_file)
    ctx.use_privatekey_file(pkey_file)
    return ctx
933149
function getHttpsCerts(callback) {
  // Certs are stored under a tmp path, ensure it exists.
  var certPath = path.join(os.tmpDir(), 'wtf-instrument-certs');
  if (!fs.existsSync(certPath)) {
    fs.mkdirSync(certPath);
  }
  var cnfPath = path.join(certPath, 'openssl.cnf');
  var privateKeyPath = path.join(certPath, 'privatekey.pem');
  var certRequestPath = path.join(certPath, 'certrequest.csr');
  var certificatePath = path.join(certPath, 'certificate.pem');

  // If the cert files are not found, create them.
  if (!fs.existsSync(path.join(certPath, 'privatekey.pem'))) {
    console.log('Generating new HTTPS certs...');
    // openssl genrsa -out privatekey.pem 1024
    // openssl req -new -key privatekey.pem -out certrequest.csr
    // openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem

    // Note that to do this sliently we need to write this conf file.
    fs.writeFileSync(cnfPath, [
      '[req]',
      'prompt = no',
      'distinguished_name = req_distinguished_name',
      '[req_distinguished_name]',
      'C = GB',
      'ST = Test State',
      'L = Test Locality',
      'O = Org Name',
      'OU = Org Unit Name',
      'CN = Common Name',
      'emailAddress = test@email.com'
    ].join('\n'));

    child_process.exec([
      'openssl genrsa -out ' + privateKeyPath + ' 1024',
      'openssl req -config ' + cnfPath + ' -new -key ' + privateKeyPath + ' -out ' + certRequestPath,
      'openssl x509 -req -in ' + certRequestPath + ' -signkey ' + privateKeyPath + ' -out ' + certificatePath,
    ].join(' && '), function(error, stdout, stderr) {
      readCerts();
    });
  } else {
    readCerts();
  }

  function readCerts() {
    var privateKey = fs.readFileSync(
        path.join(certPath, 'privatekey.pem')).toString();
    var certificate = fs.readFileSync(
        path.join(certPath, 'certificate.pem')).toString();
    callback({
      privateKey: privateKey,
      certificate: certificate
    });
  };
}
698500
private ArrayList<String> searchAccurateAliases(String[] keyTypes, Principal[] issuers) {
    if (keyTypes == null || keyTypes.length == 0) {
      return null;
    }

    ArrayList<String> accurateAliases = new ArrayList<>();
    for (Map.Entry<String, KeyStore.PrivateKeyEntry> mapEntry : privateKeyHash.entrySet()) {

      Certificate[] certs = mapEntry.getValue().getCertificateChain();
      String alg = certs[0].getPublicKey().getAlgorithm();

      for (String keyType : keyTypes) {
        if (alg.equals(keyType)) {
          if (issuers != null && issuers.length != 0) {
            checkLoop:
            for (Certificate cert : certs) {
              if (cert instanceof X509Certificate) {
                X500Principal certificateIssuer = ((X509Certificate) cert).getIssuerX500Principal();
                for (Principal issuer : issuers) {
                  if (certificateIssuer.equals(issuer)) {
                    accurateAliases.add(mapEntry.getKey());
                    break checkLoop;
                  }
                }
              }
            }
          } else {
            accurateAliases.add(mapEntry.getKey());
          }
        }
      }
    }
    return accurateAliases;
  }
55430
def queryAll(self, queryString):
    '''
    
    '''
    self._setHeaders('queryAll')
    return self._sforce.service.queryAll(queryString)
924485
public static sslservice[] get_filtered(nitro_service service, String filter) throws Exception{
		sslservice obj = new sslservice();
		options option = new options();
		option.set_filter(filter);
		sslservice[] response = (sslservice[]) obj.getfiltered(service, option);
		return response;
	}
678147
def list_ipsecpolicies(self, retrieve_all=True, **_params):
        """"""
        return self.list('ipsecpolicies',
                         self.ipsecpolicies_path,
                         retrieve_all,
                         **_params)
1230626
def _certifi_where_for_ssl_version():
    
    if not ssl:
        return

    if ssl.OPENSSL_VERSION_INFO < (1, 0, 2):
        warnings.warn(
            'You are using an outdated version of OpenSSL that '
            'can\'t use stronger root certificates.')
        return certifi.old_where()

    return certifi.where()
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;
    }
347455
def search(self, *args, **kwargs):
        """"""
        ret = []
        for record in Handler.ALL_VERS_DATA.values():
            matchArgs = list(kwargs.keys())
            for k,v in iteritems(kwargs): # restrict records based on key-value match requirement
                try:
                    if record[k] != v: break # a non-matching requirement means this record doesn't match
                except: break # record doesn't have required key 'k'
                matchArgs.remove(k)
            if matchArgs: continue # didn't match all required kwargs
            matchArgs = list(args)
            for k,v in iteritems(record): # find any record with a <value> in it
                if k in matchArgs: matchArgs.remove(k)
                if v in matchArgs: matchArgs.remove(v)
            if matchArgs: continue # didn't match all required args
            ret.append(record)
        return ret
1105110
def filter_pem(data):
    '''
    '''
    assert isinstance(data, bytes), 'Expect bytes. Got {}.'.format(type(data))
    certs = set()
    new_list = []
    in_pem_block = False

    for line in re.split(br'[\r\n]+', data):
        if line == b'-----BEGIN CERTIFICATE-----':
            assert not in_pem_block
            in_pem_block = True
        elif line == b'-----END CERTIFICATE-----':
            assert in_pem_block
            in_pem_block = False

            content = b''.join(new_list)
            content = rewrap_bytes(content)

            certs.add(b'-----BEGIN CERTIFICATE-----\n' +
                      content +
                      b'\n-----END CERTIFICATE-----\n')

            new_list = []
        elif in_pem_block:
            new_list.append(line)

    return certs
184047
def get_cert_types(self):
        
        result = self.client.service.getCustomerCertTypes(authData=self.auth)

        if result.statusCode == 0:
            return jsend.success({'cert_types': result.types})
        else:
            return self._create_error(result.statusCode)
657292
def query(path, method='GET', data=None, params=None, header_dict=None, decode=True):
    '''
    
    '''
    certificate_path = config.get_cloud_config_value(
        'certificate_path',
        get_configured_provider(), __opts__, search_global=False
    )
    subscription_id = salt.utils.stringutils.to_str(
        config.get_cloud_config_value(
            'subscription_id',
            get_configured_provider(), __opts__, search_global=False
        )
    )
    management_host = config.get_cloud_config_value(
        'management_host',
        get_configured_provider(),
        __opts__,
        search_global=False,
        default='management.core.windows.net'
    )
    backend = config.get_cloud_config_value(
        'backend',
        get_configured_provider(), __opts__, search_global=False
    )
    url = 'https://{management_host}/{subscription_id}/{path}'.format(
        management_host=management_host,
        subscription_id=subscription_id,
        path=path,
    )

    if header_dict is None:
        header_dict = {}

    header_dict['x-ms-version'] = '2014-06-01'

    result = salt.utils.http.query(
        url,
        method=method,
        params=params,
        data=data,
        header_dict=header_dict,
        port=443,
        text=True,
        cert=certificate_path,
        backend=backend,
        decode=decode,
        decode_type='xml',
    )
    if 'dict' in result:
        return result['dict']
    return
865654
def list(gandi, id, altnames, csr, cert, all_status, status, dates, limit):
    
    options = {'items_per_page': limit}

    if not all_status:
        options['status'] = ['valid', 'pending']

    output_keys = ['cn', 'plan']

    if id:
        output_keys.append('id')

    if status:
        output_keys.append('status')

    if dates:
        output_keys.extend(['date_created', 'date_end'])

    if altnames:
        output_keys.append('altnames')

    if csr:
        output_keys.append('csr')

    if cert:
        output_keys.append('cert')

    result = gandi.certificate.list(options)
    for num, cert in enumerate(result):
        if num:
            gandi.separator_line()
        cert['plan'] = package_desc(gandi, cert['package'])
        output_cert(gandi, cert, output_keys)

    return result
154861
public static ssl_cert[] get(nitro_service client) throws Exception
	{
		ssl_cert resource = new ssl_cert();
		resource.validate("get");
		return (ssl_cert[]) resource.get_resources(client);
	}
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}