Builds a CERT record from a Certificate
164816
public static CERTRecord
buildRecord(Name name, int dclass, long ttl, Certificate cert) {
	return buildRecord(name, dclass, ttl, cert, 0, 0);
}
32015
def parse_space_delimited_cert(raw_cert)
      cert_contents = raw_cert.split(' ')
      # "-----BEGIN CERTIFICATE------" fix
      cert_contents[0] += " #{cert_contents.delete_at(1)}"
      # "-----END CERTIFICATE------" fix
      cert_contents[-1] = "#{cert_contents[-2]} #{cert_contents.delete_at(-1)}"

      cert_contents.map { |el| "\\t#{el}" } # Hack it to match expected syntax
    end
352423
function readCertificateDataFromFile ({ keyFile, certFile, caFile }) {
  let key, cert, ca;

  if (keyFile) {
    key = fs.readFileSync(keyFile);
  }

  if (certFile) {
    cert = fs.readFileSync(certFile);
  }

  if (caFile) {
    ca = fs.readFileSync(caFile);
  }

  return { key, cert, ca };
}
257426
def certificate(self, value):
        """"""
        import os
        if os.path.isfile(value):
            self._certificatefile = value
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
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();
  }
687467
def serialize_cert_to_pem(cert_obj):
    
    return cert_obj.public_bytes(
        encoding=cryptography.hazmat.primitives.serialization.Encoding.PEM
    )
326992
def insert(self, cert_p):
        
        return lib.zcertstore_insert(self._as_parameter_, byref(zcert_p.from_param(cert_p)))
325064
def _parse_ssl_options(options):
    """"""
    use_ssl = options.get('ssl')
    if use_ssl is not None:
        validate_boolean('ssl', use_ssl)

    certfile = options.get('ssl_certfile')
    keyfile = options.get('ssl_keyfile')
    passphrase = options.get('ssl_pem_passphrase')
    ca_certs = options.get('ssl_ca_certs')
    cert_reqs = options.get('ssl_cert_reqs')
    match_hostname = options.get('ssl_match_hostname', True)
    crlfile = options.get('ssl_crlfile')

    ssl_kwarg_keys = [k for k in options
                      if k.startswith('ssl_') and options[k]]
    if use_ssl == False and ssl_kwarg_keys:
        raise ConfigurationError("ssl has not been enabled but the "
                                 "following ssl parameters have been set: "
                                 "%s. Please set `ssl=True` or remove."
                                 % ', '.join(ssl_kwarg_keys))

    if ssl_kwarg_keys and use_ssl is None:
        # ssl options imply ssl = True
        use_ssl = True

    if use_ssl is True:
        ctx = get_ssl_context(
            certfile,
            keyfile,
            passphrase,
            ca_certs,
            cert_reqs,
            crlfile,
            match_hostname)
        return ctx, match_hostname
    return None, match_hostname
1313801
def getCert(username, password,
            certHost=_SERVER,
            certfile=None,
            certQuery=_PROXY):
    """"""

    if certfile is None:
        certfile = tempfile.NamedTemporaryFile()

    # Add the username and password.
    # If we knew the realm, we could use it instead of ``None``.
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
    top_level_url = "http://" + certHost
    logging.debug(top_level_url)
    password_mgr.add_password(None, top_level_url, username, password)
    handler = urllib2.HTTPBasicAuthHandler(password_mgr)
    logging.debug(str(handler))
    # create "opener" (OpenerDirector instance)
    opener = urllib2.build_opener(handler)

    # Install the opener.   
    urllib2.install_opener(opener)

    # buuld the url that with 'GET' a certificat using user_id/password info
    url = "http://" + certHost + certQuery
    logging.debug(url)

    r = None
    try:
        r = opener.open(url)
    except urllib2.HTTPError as e:
        logging.debug(url)
        logging.debug(str(e))
        return False

    logging.debug(str(r))

    if r is not None:
        while True:
            buf = r.read()
            logging.debug(buf)
            if not buf:
                break
            certfile.write(buf)
        r.close()

    return certfile
1253751
def certificate_object(self):
        
        if not self.certificate:
            return None
        self.certificate.seek(0)
        return crypto.parse_certificate(self.certificate.read())
1056943
def verify_cert(self):
        '''
        
        '''
        log.debug('Verifying the %s certificate, keyfile: %s',
                  self.certificate, self.keyfile)
        try:
            ssl.create_default_context().load_cert_chain(self.certificate, keyfile=self.keyfile)
        except ssl.SSLError:
            error_string = 'SSL certificate and key do not match'
            log.error(error_string)
            raise SSLMismatchException(error_string)
        except IOError:
            log.error('Unable to open either certificate or key file')
            raise
        log.debug('Certificate looks good.')
743926
def _cert_file(name, cert_type):
    '''
    
    '''
    return os.path.join(LE_LIVE, name, '{0}.pem'.format(cert_type))
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)
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))
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,
    )
1268058
public static ResourceRecordSet<CERTData> cert(String name, Collection<String> certdata) {
    return new CERTBuilder().name(name).addAll(certdata).build();
  }