Really only necessary until I implement a direct API route to search for certificates...
439143
public function findCertificate($name)
    {
        foreach ($this->accounttypes as $type) {
            foreach ($this->accounts[$type] as $account) {
                // Skip empty accounts with no visible certificates
                if (!isset($account['certificates'])) {
                   continue;
                }
                foreach ($account['certificates'] as $certificate) {
                    if ($certificate['name'] == $name) {
                        $certificate['accounttype'] = $type;
                        $certificate['pemurl'] = $this->baseurl.'/'.$type.'/accounts/'.$certificate['account_id'].'/certificates/'.$certificate['id'].'/pem';

                        return $certificate;
                    }
                }
            }
        }
    }
766132
static void verifyCAKeyUsage(X509Certificate cert)
            throws CertPathValidatorException {
        String msg = "CA key usage";
        if (debug != null) {
            debug.println("KeyChecker.verifyCAKeyUsage() ---checking " + msg
                          + "...");
        }

        boolean[] keyUsageBits = cert.getKeyUsage();

        // getKeyUsage returns null if the KeyUsage extension is not present
        // in the certificate - in which case there is nothing to check
        if (keyUsageBits == null) {
            return;
        }

        // throw an exception if the keyCertSign bit is not set
        if (!keyUsageBits[KEY_CERT_SIGN]) {
            throw new CertPathValidatorException
                (msg + " check failed: keyCertSign bit is not set", null,
                 null, -1, PKIXReason.INVALID_KEY_USAGE);
        }

        if (debug != null) {
            debug.println("KeyChecker.verifyCAKeyUsage() " + msg
                          + " verified.");
        }
    }
1322962
private void load() throws IOException
    {
        if ( !knownHosts.exists() )
        {
            return;
        }

        assertKnownHostFileReadable();

        try ( BufferedReader reader = new BufferedReader( new FileReader( knownHosts ) ) )
        {
            String line;
            while ( (line = reader.readLine()) != null )
            {
                if ( (!line.trim().startsWith( "#" )) )
                {
                    String[] strings = line.split( " " );
                    if ( strings[0].trim().equals( serverId ) )
                    {
                        // load the certificate
                        fingerprint = strings[1].trim();
                        return;
                    }
                }
            }
        }
    }
162528
def _get_tls_object(self, ssl_params):
        
        if ssl_params is None:
            return None

        if not ssl_params["verify"] and ssl_params["ca_certs"]:
            self.warning(
                "Incorrect configuration: trying to disable server certificate validation, "
                "while also specifying a capath. No validation will be performed. Fix your "
                "configuration to remove this warning"
            )

        validate = ssl.CERT_REQUIRED if ssl_params["verify"] else ssl.CERT_NONE

        if ssl_params["ca_certs"] is None or os.path.isfile(ssl_params["ca_certs"]):
            tls = ldap3.core.tls.Tls(
                local_private_key_file=ssl_params["key"],
                local_certificate_file=ssl_params["cert"],
                ca_certs_file=ssl_params["ca_certs"],
                version=ssl.PROTOCOL_SSLv23,
                validate=validate,
            )
        elif os.path.isdir(ssl_params["ca_certs"]):
            tls = ldap3.core.tls.Tls(
                local_private_key_file=ssl_params["key"],
                local_certificate_file=ssl_params["cert"],
                ca_certs_path=ssl_params["ca_certs"],
                version=ssl.PROTOCOL_SSLv23,
                validate=validate,
            )
        else:
            raise ConfigurationError(
                'Invalid path {} for ssl_ca_certs: no such file or directory'.format(ssl_params['ca_certs'])
            )
        return tls
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
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();
  }
1114800
function(bs, done) {
        if (
            _.isUndefined(bs.options.get("online")) &&
            _.isUndefined(process.env.TESTING)
        ) {
            require("dns").resolve("www.google.com", function(err) {
                var online = false;
                if (err) {
                    bs.debug(
                        "Could not resolve www.google.com, setting {magenta:online: false}"
                    );
                } else {
                    bs.debug(
                        "Resolved www.google.com, setting {magenta:online: true}"
                    );
                    online = true;
                }
                done(null, {
                    options: {
                        online: online
                    }
                });
            });
        } else {
            done();
        }
    }
627755
public static function _requireSSL() {
        if (!self::_isSSL()) {
            if (isset($_SERVER) && isset($_SERVER['HTTP_HOST']) && isset($_SERVER['REQUEST_URI'])) {
                header("HTTP/1.1 301 Moved Permanently");
                header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
                exit();
            } else {
                _Log::fatal('$_SERVER variables are not set.  Unable to require SSL');
                throw new _Exception('$_SERVER variables are not set.  Unable to require SSL');
            }
        }
    }
324467
def show_cert(id_):
    '''
    
    '''
    data = __utils__['http.query'](
        '{0}/certificaterequests/{1}/certificate'.format(_base_url(), id_),
        params={
            'format': 'PEM',
            'chainOrder': 'ROOT_FIRST'
        },
        status=True,
        text=True,
        header_dict={'tppl-api-key': _api_key()},
    )
    status = data['status']
    if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
        raise CommandExecutionError(
            'There was an API error: {0}'.format(data['error'])
        )
    data = data.get('body', '')
    csr_data = __utils__['http.query'](
        '{0}/certificaterequests/{1}'.format(_base_url(), id_),
        status=True,
        decode=True,
        decode_type='json',
        header_dict={'tppl-api-key': _api_key()},
    )
    status = csr_data['status']
    if six.text_type(status).startswith('4') or six.text_type(status).startswith('5'):
        raise CommandExecutionError(
            'There was an API error: {0}'.format(csr_data['error'])
        )
    csr_data = csr_data.get('dict', {})
    certs = _parse_certs(data)
    dns_name = ''
    for item in csr_data['certificateName'].split(','):
        if item.startswith('cn='):
            dns_name = item.split('=')[1]
    #certs['CSR Data'] = csr_data

    cache = salt.cache.Cache(__opts__, syspaths.CACHE_DIR)
    domain_data = cache.fetch('venafi/domains', dns_name)
    if domain_data is None:
        domain_data = {}
    certs['private_key'] = domain_data.get('private_key')
    domain_data.update(certs)
    cache.store('venafi/domains', dns_name, domain_data)

    certs['request_id'] = id_
    return certs
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
760494
function needsToLoadEC2IAMRoleCredentials() {
		if (!accessKey || !secretKey) return true;
		if (credentialsExpiration === null) return false;
		return (credentialsExpiration.getTime() - Date.now()) < CREDENTIALS_EXPIRATION_THRESHOLD;
	}
221374
def search_url(*args)
      options = args.extract_options!.stringify_keys!
      protocol = (options.delete('protocol') || self.protocol).to_s
      
      uri = search_uri
      uri.scheme = protocol
      uri.query = ["key=#{api_key}", "q=#{URI.escape(args.join(','))}", *options.map{ |k,v| "#{k}=#{v}" }].join('&')
      p uri.to_s if self.debug
      return uri
    end
1205936
function Requests(apiUrl, version, publicKey) {
    this.apiUrl = stripSlashes(apiUrl);
    this.version = version.toString();
    this.publicKey = publicKey;
}
277955
def ssl_required(allow_non_ssl=False):
    
    def wrapper(view_func):
        def _checkssl(request, *args, **kwargs):
            # allow_non_ssl=True lets non-https requests to come
            # through to this view (and hence not redirect)
            if hasattr(settings, 'SSL_ENABLED') and settings.SSL_ENABLED \
                    and not request.is_secure() and not allow_non_ssl:
                return HttpResponseRedirect(
                    request.build_absolute_uri().replace('http://', 'https://'))
            return view_func(request, *args, **kwargs)

        return _checkssl
    return wrapper
890023
def gen_cert_request(filepath, keyfile, config, silent=False):
    
    message = 'generate ssl certificate request'
    cmd = (
        'openssl req -new -key {} -out {} -subj "{}"'
        ' -extensions v3_req -config {}').format(
            keyfile, filepath, SUBJECT, config)
    call_openssl(cmd, message, silent)
1301534
function (cert, cb) {
    var infoObject = {},
        subjectElements = [],
        err;

  	var openssl = spawn('openssl', ['req', '-noout', '-subject', '-nameopt', 'RFC2253']);

    // Catch stderr
    openssl.stderr.on('data', function (out) {
      err = new Error(out);

      // Callback and return array
  		return cb(err, infoObject);
    });

    openssl.stdout.on('data', function (out) {
      var data = out.toString();

      // Put each line into an array
      var lineArray = data.split('\n');

      // Filter out empty ones
      lineArray = lineArray.filter(function(n){ return n !== undefined && n !== '' });

      /* Construct infoObject */

      // Certificate
      infoObject.certificate = cert;

      // Subject
      infoObject.subject = {};
      // Split by "/" prefix
      subjectElements = lineArray[0].replace('subject=', '').split(',');
      // For each elements
      for (var iS = 0; iS < subjectElements.length; iS++) {
        // Split keys and values by "=" separator
        var subjectKeyValue = subjectElements[iS].split('=');
        infoObject.subject[subjectKeyValue[0]] = subjectKeyValue[1];
      }

      // Callback and return array
  		return cb(err, infoObject);
  	});

  	openssl.stdin.write(cert);
  	openssl.stdin.end();
  }
843397
def _query_api(self, params, direct=False):
        
        if not direct:
            return get(
                self.URI_BASE + self.RESOURCE_NAME, params=params, headers=self._headers
            )

        id = params.pop("id")
        return get(
            self.URI_BASE + self.RESOURCE_NAME + "/{0}".format(id),
            params=params,
            headers=self._headers,
        )