Verify that the certificate was issued for the given hostname.

        Raises:
            CertificateError: If the certificate was not issued for the supplied hostname.
960648
def matches_hostname(cls, certificate: cryptography.x509.Certificate, hostname: str) -> None:
        
        # Extract the names from the certificate to create the properly-formatted dictionary
        certificate_names = {
            'subject': (tuple([('commonName', name) for name in cls.get_common_names(certificate.subject)]),),
            'subjectAltName': tuple([('DNS', name) for name in cls.get_dns_subject_alternative_names(certificate)]),
        }
        # CertificateError is raised on failure
        ssl.match_hostname(certificate_names, hostname)
1167879
def _verify(self):
        """"""
        if not self.keyid:
            raise ValueError('No GPG key specified for signing, did you mean to use --no-sign?')
        sign = self.gpg.sign('', keyid=self.keyid)
        if 'secret key not available' in sign.stderr:
            raise ValueError('Key not found')
        elif 'NEED_PASSPHRASE' in sign.stderr:
            self.passphrase = getpass.getpass('Passphrase for GPG key: ')
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])
1094729
def _get_ssl_validation(self, value):
        
        return self._get_ssl_attribute(value, compatibility.SSL_CERT_MAP,
                                       ssl.CERT_NONE,
                                       'ssl_options: cert_reqs \'%s\' not '
                                       'found falling back to CERT_NONE.')
370505
def verifyCert(self, cert):
        
        tbsCert = cert.tbsCertificate
        sigAlg = tbsCert.signature
        h = hash_by_oid[sigAlg.algorithm.val]
        sigVal = raw(cert.signatureValue)
        return self.verify(raw(tbsCert), sigVal, h=h, t='pkcs')
1345236
def _certificate_required(cls, hostname, port=XCLI_DEFAULT_PORT,
                              ca_certs=None, validate=None):
        '''
        
        '''
        if not ca_certs:
            return False

        xlog.debug("CONNECT SSL %s:%s, cert_file=%s",
                   hostname, port, ca_certs)
        certificate = ssl.get_server_certificate((hostname, port),
                                                 ca_certs=None)
        # handle XIV pre-defined certifications
        # if a validation function was given - we let the user check
        # the certificate himself, with the user's own validate function.
        # if the validate returned True - the user checked the cert
        # and we don't need check it, so we return false.
        if validate:
            return not validate(certificate)
        return True
683504
def verify_certs(*args):
    '''
    
    '''
    msg = ("Could not find a certificate: {0}\n"
            "If you want to quickly generate a self-signed certificate, "
            "use the tls.create_self_signed_cert function in Salt")

    for arg in args:
        if not os.path.exists(arg):
            raise Exception(msg.format(arg))
1281249
def is_valid_hostname(hostname):
    ''''''
    if not isinstance(hostname, str):
        raise TypeError('hostname must be a string')
    # strip exactly one dot from the right, if present
    if hostname and hostname[-1] == ".":
        hostname = hostname[:-1]
    if not hostname or len(hostname) > 253:
        return False
    labels = hostname.split('.')
    # the TLD must be not all-numeric
    if re.match(NUMERIC_REGEX, labels[-1]):
        return False
    return all(LABEL_REGEX.match(label) for label in labels)
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
614357
def _verify_sig(self, m, cert):
        
        if self.sig_val:
            if self.sig_alg:
                h, sig = _tls_hash_sig[self.sig_alg].split('+')
                if sig.endswith('pss'):
                    t = "pss"
                else:
                    t = "pkcs"
                return cert.verify(m, self.sig_val, t=t, h=h)
            else:
                if self.tls_session.tls_version >= 0x0300:
                    return cert.verify(m, self.sig_val, t='pkcs', h='md5-sha1')
                else:
                    return cert.verify(m, self.sig_val, t='pkcs', h='md5')
        return False
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
1218993
def check_sp_certs(self):
        
        key = self.get_sp_key()
        cert = self.get_sp_cert()
        return key is not None and cert is not None
316024
def _request_host(self):
        """"""
        urlstr = 'https://%s/xmldata?item=all' % (self.host)
        kwargs = {}
        if self.cacert is not None:
            kwargs['verify'] = self.cacert
        else:
            kwargs['verify'] = False
        try:
            response = requests.get(urlstr, **kwargs)
            response.raise_for_status()
        except Exception as e:
            raise IloConnectionError(e)

        return response.text
33443
def check_that_request_is_valid(signature_certificate_url, request, raw_body)
      certificate, chain = AlexaVerifier::CertificateStore.fetch(signature_certificate_url) if @configuration.verify_certificate? || @configuration.verify_signature?

      begin
        AlexaVerifier::Verifier::CertificateVerifier.valid!(certificate, chain) if @configuration.verify_certificate?

        check_that_request_was_signed(certificate.public_key, request, raw_body) if @configuration.verify_signature?
      rescue AlexaVerifier::InvalidCertificateError, AlexaVerifier::InvalidRequestError => error
        # We don't want to cache a certificate that fails our checks as it could lock us out of valid requests for the cache length
        AlexaVerifier::CertificateStore.delete(signature_certificate_url)

        raise error
      end
    end
947335
def check(self, url_data):
        
        host = url_data.urlparts[1]
        if host in self.checked_hosts:
            return
        self.checked_hosts.add(host)
        cert = url_data.ssl_cert
        config = url_data.aggregate.config
        if cert and 'notAfter' in cert:
            self.check_ssl_valid_date(url_data, cert)
        elif config['sslverify']:
            msg = _('certificate did not include "notAfter" information')
            url_data.add_warning(msg)
        else:
            msg = _('SSL verification is disabled; enable the sslverify option')
            url_data.add_warning(msg)
1276199
def _check_certificate(self):
        
        if (self.file_name.startswith("jdk-") and self.repo == "sbo" and
                self.downder == "wget"):
            certificate = (' --no-check-certificate --header="Cookie: '
                           'oraclelicense=accept-securebackup-cookie"')
            self.msg.template(78)
            print("| '{0}' need to go ahead downloading".format(
                certificate[:23].strip()))
            self.msg.template(78)
            print("")
            self.downder_options += certificate
            if not self.msg.answer() in ["y", "Y"]:
                raise SystemExit()
590661
def is_valid_url(value):
    
    match = URL_REGEX.match(value)
    host_str = urlparse(value).hostname
    return match and is_valid_host(host_str)