Determines if a certificate is self-signed

    :param cert:
        An asn1crypto.x509.Certificate object to check

    :return:
        A boolean - True if the certificate is self-signed, False otherwise
338541
def _self_signed(cert):
    

    self_signed = cert.self_signed

    if self_signed == 'yes':
        return True
    if self_signed == 'no':
        return False

    # In the case of "maybe", we have to check the signature
    signature_algo = cert['signature_algorithm'].signature_algo
    hash_algo = cert['signature_algorithm'].hash_algo

    if signature_algo == 'rsassa_pkcs1v15':
        verify_func = asymmetric.rsa_pkcs1v15_verify
    elif signature_algo == 'dsa':
        verify_func = asymmetric.dsa_verify
    elif signature_algo == 'ecdsa':
        verify_func = asymmetric.ecdsa_verify
    else:
        raise PathValidationError(pretty_message(
            '''
            Unable to verify the signature of the certificate since it uses
            the unsupported algorithm %s
            ''',
            signature_algo
        ))

    try:
        key_object = asymmetric.load_certificate(cert)
        verify_func(key_object, cert['signature_value'].native, cert['tbs_certificate'].dump(), hash_algo)
        return True

    except (oscrypto.errors.SignatureError):
        return False
774767
private function _checkUniqueID(Certificate $cert): bool
    {
        if (!$cert->tbsCertificate()->hasIssuerUniqueID()) {
            return false;
        }
        $uid = $cert->tbsCertificate()
            ->issuerUniqueID()
            ->string();
        if ($this->_issuerUID->string() != $uid) {
            return false;
        }
        return true;
    }
809719
def validate_key_usage(loaded_cert):
    
    try:
        key_usage = loaded_cert.extensions.get_extension_for_oid(
            x509.oid.ExtensionOID.KEY_USAGE
        )
        if not key_usage.value.digital_signature:
            raise ValueError(
                "Certificate is using the keyUsage extension, but has "
                "not asserted the Digital Signature bit."
            )
    except x509.ExtensionNotFound:  # keyUsage extension not used
        return
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
773533
public function identifiesPKC(Certificate $cert): bool
    {
        // if neither baseCertificateID nor entityName are present
        if (!$this->_baseCertificateID && !$this->_entityName) {
            return false;
        }
        // if baseCertificateID is present, but doesn't match
        if ($this->_baseCertificateID &&
             !$this->_baseCertificateID->identifiesPKC($cert)) {
            return false;
        }
        // if entityName is present, but doesn't match
        if ($this->_entityName && !$this->_checkEntityName($cert)) {
            return false;
        }
        return true;
    }
832305
private void verifySignature(X509Certificate cert)
        throws CertPathValidatorException
    {
        String msg = "signature";
        if (debug != null)
            debug.println("---checking " + msg + "...");

        try {
            if (sigProvider != null) {
                cert.verify(prevPubKey, sigProvider);
            } else {
                cert.verify(prevPubKey);
            }
        } catch (SignatureException e) {
            throw new CertPathValidatorException
                (msg + " check failed", e, null, -1,
                 BasicReason.INVALID_SIGNATURE);
        } catch (GeneralSecurityException e) {
            throw new CertPathValidatorException(msg + " check failed", e);
        }

        if (debug != null)
            debug.println(msg + " verified.");
    }
1049867
private boolean verifySignature(X509Certificate cert)
        throws CertPathValidatorException {

        try {
            Signature respSignature = Signature.getInstance(sigAlgId.getName());
            respSignature.initVerify(cert.getPublicKey());
            respSignature.update(tbsResponseData);

            if (respSignature.verify(signature)) {
                if (debug != null) {
                    debug.println("Verified signature of OCSP Response");
                }
                return true;

            } else {
                if (debug != null) {
                    debug.println(
                        "Error verifying signature of OCSP Response");
                }
                return false;
            }
        } catch (InvalidKeyException | NoSuchAlgorithmException |
                 SignatureException e)
        {
            throw new CertPathValidatorException(e);
        }
    }
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
1140342
def verifyCertificate(self, name):
        
        certPath = os.path.join(self.basePath, self.DIR_CERTS, '%s.cert.pem' % name)
        if not os.path.isfile(certPath):
            raise ValueError('Certificate [%s] not found' % certPath)
        if subprocess.call([ 'openssl', 'x509', '-noout', '-text', '-in', certPath ]) != 0:
            raise ValueError('Failed to verify the certificate')
1261315
def deleteCertificate(self, certName):
        

        params = {"f" : "json"}
        url = self._url + "/sslCertificates/{cert}/delete".format(
            cert=certName)
        return self._post(url=url, param_dict=params,
                          proxy_port=self._proxy_port,
                          proxy_url=self._proxy_url)
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
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))
291410
def Verify(self, public_key):
    
    # TODO(amoser): We have to do this manually for now since cryptography does
    # not yet support cert verification. There is PR 2460:
    # https://github.com/pyca/cryptography/pull/2460/files
    # that will add it, once it's in we should switch to using this.

    # Note that all times here are in UTC.
    now = rdfvalue.RDFDatetime.Now().AsDatetime()
    if now > self._value.not_valid_after:
      raise VerificationError("Certificate expired!")
    if now < self._value.not_valid_before:
      raise VerificationError("Certificate not yet valid!")

    public_key.Verify(
        self._value.tbs_certificate_bytes,
        self._value.signature,
        hash_algorithm=self._value.signature_hash_algorithm)
    return True
1089637
def cert
      @cert ||= OpenSSL::X509::Certificate.new.tap do |c|
        c.subject = c.issuer = OpenSSL::X509::Name.parse(cert_subject)
        c.not_before = Time.now
        c.not_after = Time.now + 365 * 24 * 60 * 60
        c.public_key = cert_key
        c.serial = 0x1
        c.version = 0x0
        c.sign cert_key, ::U2F::DIGEST.new
      end
    end
581511
private static boolean issues(X509CertImpl cert, X509CRLImpl crl,
                                  String provider) throws IOException
    {
        boolean matched = false;

        AdaptableX509CertSelector issuerSelector =
                                    new AdaptableX509CertSelector();

        // check certificate's key usage
        boolean[] usages = cert.getKeyUsage();
        if (usages != null) {
            usages[6] = true;       // cRLSign
            issuerSelector.setKeyUsage(usages);
        }

        // check certificate's subject
        X500Principal crlIssuer = crl.getIssuerX500Principal();
        issuerSelector.setSubject(crlIssuer);

        /*
         * Facilitate certification path construction with authority
         * key identifier and subject key identifier.
         *
         * In practice, conforming CAs MUST use the key identifier method,
         * and MUST include authority key identifier extension in all CRLs
         * issued. [section 5.2.1, RFC 2459]
         */
        AuthorityKeyIdentifierExtension crlAKID = crl.getAuthKeyIdExtension();
        if (crlAKID != null) {
            issuerSelector.parseAuthorityKeyIdentifierExtension(crlAKID);
        }

        matched = issuerSelector.match(cert);

        // if AKID is unreliable, verify the CRL signature with the cert
        if (matched && (crlAKID == null ||
                cert.getAuthorityKeyIdentifierExtension() == null)) {
            try {
                crl.verify(cert.getPublicKey(), provider);
                matched = true;
            } catch (GeneralSecurityException e) {
                matched = false;
            }
        }

        return matched;
    }
1302141
def _are_certificates_identical(self):
        
        sni_cert = self.sni_data.get("Certificate_details")
        non_sni_cert = self.non_sni_data.get("Certificate_details")
        if all(cert for cert in (sni_cert, non_sni_cert) if cert) and sni_cert == non_sni_cert:
            return True
        return
611474
public static boolean verify(final String name, final X509Certificate cert) {
        try {
        	verifier.verify(name, cert);
            return true;
        } catch (final SSLException ex) {
        	// this is only logged here because eventually a CertificateException will be throw in verifyAndThrow.
        	// If this method is called in another method, the caller should be responsible to throw exceptions,
            logger.error(ex.getMessage(), ex);
            
            return false;
        }
    }