stuff for checking certificate
488137
private void checkCertificateExpiryDate(URL url, List<Metric> metrics) throws Exception {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(final String arg0, final SSLSession arg1) {
                return true;
            }
        });
        List<Date> expiryDates = new ArrayList<Date>();
        conn.getResponseCode();
        Certificate[] certs = conn.getServerCertificates();
        for (Certificate cert : certs) {
            X509Certificate x509 = (X509Certificate) cert;
            Date expiry = x509.getNotAfter();
            expiryDates.add(expiry);
        }

        conn.disconnect();
        Date today = new Date();
        for (Date date : expiryDates) {
            int diffInDays = (int) ((date.getTime() - today.getTime()) / (1000 * 60 * 60 * 24));
            metrics.add(new Metric("certificate", "", new BigDecimal(diffInDays), null, null));
        }
    }
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.')
516623
def _get_and_verify_certificate_chain(
            server_info: ServerConnectivityInfo,
            trust_store: TrustStore
    ) -> Tuple[List[Certificate], str, Optional[OcspResponse]]:
        
        ssl_connection = server_info.get_preconfigured_ssl_connection(ssl_verify_locations=trust_store.path)

        # Enable OCSP stapling
        ssl_connection.ssl_client.set_tlsext_status_ocsp()

        try:  # Perform the SSL handshake
            ssl_connection.connect()

            ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp()
            x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain()
            (_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result()

        except ClientCertificateRequested:  # The server asked for a client cert
            # We can get the server cert anyway
            ocsp_response = ssl_connection.ssl_client.get_tlsext_status_ocsp_resp()
            x509_cert_chain = ssl_connection.ssl_client.get_peer_cert_chain()
            (_, verify_str) = ssl_connection.ssl_client.get_certificate_chain_verify_result()

        finally:
            ssl_connection.close()

        # Parse the certificates using the cryptography module
        parsed_x509_chain = [load_pem_x509_certificate(x509_cert.as_pem().encode('ascii'), backend=default_backend())
                             for x509_cert in x509_cert_chain]
        return parsed_x509_chain, verify_str, ocsp_response
926385
def _verify_cert(self, sock: ssl.SSLSocket):
        ''''''
        # Based on tornado.iostream.SSLIOStream
        # Needed for older OpenSSL (<0.9.8f) versions
        verify_mode = self._ssl_context.verify_mode

        assert verify_mode in (ssl.CERT_NONE, ssl.CERT_REQUIRED,
                               ssl.CERT_OPTIONAL), \
            'Unknown verify mode {}'.format(verify_mode)

        if verify_mode == ssl.CERT_NONE:
            return

        cert = sock.getpeercert()

        if not cert and verify_mode == ssl.CERT_OPTIONAL:
            return

        if not cert:
            raise SSLVerificationError('No SSL certificate given')

        try:
            ssl.match_hostname(cert, self._hostname)
        except ssl.CertificateError as error:
            raise SSLVerificationError('Invalid SSL certificate') from error
1253751
def certificate_object(self):
        
        if not self.certificate:
            return None
        self.certificate.seek(0)
        return crypto.parse_certificate(self.certificate.read())
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
319087
public function getValidatingCertificates() : array
    {
        $ret = [];
        foreach ($this->certificates as $cert) {
            /* Construct a PEM formatted certificate */
            $pemCert = "-----BEGIN CERTIFICATE-----\n".
                chunk_split($cert, 64).
                "-----END CERTIFICATE-----\n";

            /* Extract the public key from the certificate for validation. */
            $key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA256, ['type'=>'public']);
            $key->loadKey($pemCert);

            try {
                /* Check the signature. */
                if ($this->validate($key)) {
                    $ret[] = $cert;
                }
            } catch (\Exception $e) {
                /* This certificate does not sign this element. */
            }
        }

        return $ret;
    }
1032924
private static Collection<X509Certificate> getMatchingCerts
        (Collection<X509Certificate> certs, CertSelector selector) {
        // if selector not specified, all certs match
        if (selector == null) {
            return certs;
        }
        List<X509Certificate> matchedCerts = new ArrayList<>(certs.size());
        for (X509Certificate cert : certs) {
            if (selector.match(cert)) {
                matchedCerts.add(cert);
            }
        }
        return matchedCerts;
    }
1121234
def _get_certificate_obj(cert):
    '''
    
    '''
    if isinstance(cert, M2Crypto.X509.X509):
        return cert

    text = _text_or_file(cert)
    text = get_pem_entry(text, pem_type='CERTIFICATE')
    return M2Crypto.X509.load_cert_string(text)
1027733
@Override
    public void check(Certificate cert, Collection<String> unresCritExts)
        throws CertPathValidatorException
    {
        // now do the policy checks
        checkPolicy((X509Certificate) cert);

        if (unresCritExts != null && !unresCritExts.isEmpty()) {
            unresCritExts.remove(CertificatePolicies_Id.toString());
            unresCritExts.remove(PolicyMappings_Id.toString());
            unresCritExts.remove(PolicyConstraints_Id.toString());
            unresCritExts.remove(InhibitAnyPolicy_Id.toString());
        }
    }
838902
def cli(env, crt, csr, icc, key, notes):
    """"""

    template = {
        'intermediateCertificate': '',
        'certificateSigningRequest': '',
        'notes': notes,
    }
    template['certificate'] = open(crt).read()
    template['privateKey'] = open(key).read()
    if csr:
        body = open(csr).read()
        template['certificateSigningRequest'] = body

    if icc:
        body = open(icc).read()
        template['intermediateCertificate'] = body

    manager = SoftLayer.SSLManager(env.client)
    manager.add_certificate(template)
1366120
def verify_cb(conn, cert, errnum, depth, ok):
    
    if not ok:
        raise SecurityError("Could not verify CA certificate {0}"
                            .format(cert.get_subject()))
    return ok
124336
def verify_envelope(reply, key_file):
    """"""
    doc = etree.fromstring(reply)
    node = doc.find(".//{%s}Signature" % xmlsec.DSigNs)
    if node is None:
        raise CertificationError("No signature node found")
    dsigCtx = xmlsec.DSigCtx()

    xmlsec.addIDs(doc, ['Id'])
    signKey = xmlsec.Key.load(key_file, xmlsec.KeyDataFormatPem)
    signKey.name = os.path.basename(key_file)

    dsigCtx.signKey = signKey
    try:
        dsigCtx.verify(node)
    except xmlsec.VerificationError:
        return False
    return True
117021
@Override
    public void check(Certificate cert) throws CertPathValidatorException {
        check(cert, java.util.Collections.<String>emptySet());
    }
143525
def verify_certificate_chain(cert_str, trusted_certs, ignore_self_signed=True):
    

    # Load the certificate
    certificate = crypto.load_certificate(crypto.FILETYPE_ASN1, cert_str)

    # Create a certificate store and add your trusted certs
    try:
        store = crypto.X509Store()

        if ignore_self_signed:
            store.add_cert(certificate)

        # Assuming the certificates are in PEM format in a trusted_certs list
        for _cert in trusted_certs:
            store.add_cert(
                crypto.load_certificate(crypto.FILETYPE_ASN1, _cert))

        # Create a certificate context using the store and the certificate
        store_ctx = crypto.X509StoreContext(store, certificate)

        # Verify the certificate, returns None if certificate is not valid
        store_ctx.verify_certificate()

        return True

    except crypto.X509StoreContextError as e:
        raise AS2Exception('Partner Certificate Invalid: %s' % e.args[-1][-1])
555686
def verify(message, items, confirm=true)
      puts message
      puts "=================================================="

      i = 0
      items.sort.each do |item|
        i += 1
        puts "%03d.#{item}" % i
      end

      puts "=================================================="

      if confirm
        puts "Press enter to confirm or ^C to exit"
        gets
      end
    end
743681
def certs
      unless @@certs
        pattern = /-{5}BEGIN CERTIFICATE-{5}\n.*?-{5}END CERTIFICATE-{5}\n/m
        dir = @cert_directory
        certs = Dir[File.join(dir, '*.crt')].map {|f| File.read(f) }
        certs = certs.map {|c| c.scan(pattern) }.flatten
        certs.map! {|c| OpenSSL::X509::Certificate.new(c) }
        @@certs = certs.reject {|c| c.not_after < Time.now }
      end
      @@certs
    end