validates a specific certificate inside of the keystore being passed in

@param keyStore the keystore to validate against
@param cert the certificate to validate
@throws CertificateException if keystore error and unable to validate
504480
public void validate(KeyStore keyStore, Certificate cert) throws CertificateException
{
    Certificate[] certChain = null;
    
    if (cert != null && cert instanceof X509Certificate)
    {
        ((X509Certificate)cert).checkValidity();
        
        String certAlias = null;
        try
        {
            if (keyStore == null)
            {
                throw new InvalidParameterException("Keystore cannot be null");
            }

            certAlias = keyStore.getCertificateAlias((X509Certificate)cert);
            if (certAlias == null)
            {
                certAlias = "JETTY" + String.format("%016X",__aliasCount.incrementAndGet());
                keyStore.setCertificateEntry(certAlias, cert);
            }
            
            certChain = keyStore.getCertificateChain(certAlias);
            if (certChain == null || certChain.length == 0)
            {
                throw new IllegalStateException("Unable to retrieve certificate chain");
            }
        }
        catch (KeyStoreException kse)
        {
            LOG.error("Error while valid keystore", kse);
            throw new CertificateException("Unable to validate certificate" +
                    (certAlias == null ? "":" for alias [" +certAlias + "]") + ": " + kse.getMessage(), kse);
        }
        
        validate(certChain);
    } 
}
139919
@Override
    public boolean verify(final X509Certificate cert) {
        final List<String> algs = new ArrayList<String>(
                getAlgorithms(MessageDigest.class.getSimpleName()));
        Collections.sort(algs);
        int max = 0;
        for (final String alg : algs) {
            if (alg.length() > max) {
                max = alg.length();
            }
        }
        for (final String alg : algs) {
            MessageDigest digest;
            try {
                digest = MessageDigest.getInstance(alg);
            } catch (NoSuchAlgorithmException e) {
                return false;
            }
            byte[] hash;
            try {
                hash = digest.digest(cert.getEncoded());
            } catch (CertificateEncodingException e) {
                return false;
            }
            System.out.format("%" + max + "s: %s%n", alg,
                    Hex.encodeHexString(hash));
        }
        final Scanner scanner = new Scanner(System.in, Charset.defaultCharset()
                .name()).useDelimiter(String.format("%n"));
        while (true) {
            System.out.format("%nAccept? (Y/N): [N]%n");
            try {
                final String answer = scanner.next();
                System.out.println(answer);
                if (answer.equals("Y")) {
                    return true;
                } else if (answer.equals("N")) {
                    return false;
                }
            } catch (final NoSuchElementException e) {
                return false;
            }
        }
    }
1308542
public static KeyStore getKeyStore(File keyStoreFile, String keyStorePassword, String tlsStoreType)
            throws IOException {
        KeyStore keyStore = null;
        if (keyStoreFile != null && keyStorePassword != null) {
            try (InputStream inputStream = new FileInputStream(keyStoreFile)) {
                keyStore = KeyStore.getInstance(tlsStoreType);
                keyStore.load(inputStream, keyStorePassword.toCharArray());
            } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException e) {
                throw new IOException(e);
            }
        }
        return keyStore;
    }
1305317
public Sign setCertificate(Certificate certificate) {
		// If the certificate is of type X509Certificate,
		// we should check whether it has a Key Usage
		// extension marked as critical.
		if (certificate instanceof X509Certificate) {
			// Check whether the cert has a key usage extension
			// marked as a critical extension.
			// The OID for KeyUsage extension is 2.5.29.15.
			final X509Certificate cert = (X509Certificate) certificate;
			final Set<String> critSet = cert.getCriticalExtensionOIDs();

			if (CollUtil.isNotEmpty(critSet) && critSet.contains("2.5.29.15")) {
				final boolean[] keyUsageInfo = cert.getKeyUsage();
				// keyUsageInfo[0] is for digitalSignature.
				if ((keyUsageInfo != null) && (keyUsageInfo[0] == false)) {
					throw new CryptoException("Wrong key usage");
				}
			}
		}
		this.publicKey = certificate.getPublicKey();
		return this;
	}
18925
public final X509Certificate retrieveCertificate(KeyStore keyStore, String certificateName) {
        try {
            logger.entry();
            X509Certificate certificate = (X509Certificate) keyStore.getCertificate(certificateName);
            logger.exit();
            return certificate;
        } catch (KeyStoreException e) {
            RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to retrieve a certificate.", e);
            logger.error(exception.toString());
            throw exception;
        }
    }
1370806
def validate(cert, ca_name, crl_file):
    '''
    
    '''
    store = OpenSSL.crypto.X509Store()
    cert_obj = _read_cert(cert)
    if cert_obj is None:
        raise CommandExecutionError(
            'Failed to read cert from {0}, see log for details'.format(cert)
        )
    ca_dir = '{0}/{1}'.format(cert_base_path(), ca_name)
    ca_cert = _read_cert('{0}/{1}_ca_cert.crt'.format(ca_dir, ca_name))
    store.add_cert(ca_cert)
    # These flags tell OpenSSL to check the leaf as well as the
    # entire cert chain.
    X509StoreFlags = OpenSSL.crypto.X509StoreFlags
    store.set_flags(X509StoreFlags.CRL_CHECK | X509StoreFlags.CRL_CHECK_ALL)
    if crl_file is None:
        crl = OpenSSL.crypto.CRL()
    else:
        with salt.utils.files.fopen(crl_file) as fhr:
            crl = OpenSSL.crypto.load_crl(OpenSSL.crypto.FILETYPE_PEM, fhr.read())
    store.add_crl(crl)
    context = OpenSSL.crypto.X509StoreContext(store, cert_obj)
    ret = {}
    try:
        context.verify_certificate()
        ret['valid'] = True
    except OpenSSL.crypto.X509StoreContextError as e:
        ret['error'] = str(e)
        ret['error_cert'] = e.certificate
        ret['valid'] = False
    return ret
767515
static void check(PublicKey key, X509CRL crl)
                        throws CertPathValidatorException {

        X509CRLImpl x509CRLImpl = null;
        try {
            x509CRLImpl = X509CRLImpl.toImpl(crl);
        } catch (CRLException ce) {
            throw new CertPathValidatorException(ce);
        }

        AlgorithmId algorithmId = x509CRLImpl.getSigAlgId();
        check(key, algorithmId);
    }
822792
private void disableCertificateVerification()
            throws KeyManagementException, NoSuchAlgorithmException {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new CustomTrustManager() };

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new SecureRandom());
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        final HostnameVerifier verifier = new HostnameVerifier() {
            @Override
            public boolean verify(final String hostname,
                    final SSLSession session) {
                return true;
            }
        };

        HttpsURLConnection.setDefaultHostnameVerifier(verifier);
    }
696954
private static boolean verifyCertificateChain(X509Certificate cert){
		
		if ( null == cert) {
			LogUtil.writeErrorLog("cert must Not null");
			return false;
		}
		
		X509Certificate middleCert = CertUtil.getMiddleCert();
		if (null == middleCert) {
			LogUtil.writeErrorLog("middleCert must Not null");
			return false;
		}
		
		X509Certificate rootCert = CertUtil.getRootCert();
		if (null == rootCert) {
			LogUtil.writeErrorLog("rootCert or cert must Not null");
			return false;
		}
		
		try {
		
	        X509CertSelector selector = new X509CertSelector();
	        selector.setCertificate(cert);
	        
	        Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>();
	        trustAnchors.add(new TrustAnchor(rootCert, null));
	        PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(
			        trustAnchors, selector);
	
	        Set<X509Certificate> intermediateCerts = new HashSet<X509Certificate>();
	        intermediateCerts.add(rootCert);
	        intermediateCerts.add(middleCert);
	        intermediateCerts.add(cert);
	        
	        pkixParams.setRevocationEnabled(false);
	
	        CertStore intermediateCertStore = CertStore.getInstance("Collection",
	                new CollectionCertStoreParameters(intermediateCerts), "BC");
	        pkixParams.addCertStore(intermediateCertStore);
	
	        CertPathBuilder builder = CertPathBuilder.getInstance("PKIX", "BC");
	        
        	@SuppressWarnings("unused")
			PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder
                .build(pkixParams);
			LogUtil.writeLog("verify certificate chain succeed.");
			return true;
        } catch (java.security.cert.CertPathBuilderException e){
			LogUtil.writeErrorLog("verify certificate chain fail.", e);
		} catch (Exception e) {
			LogUtil.writeErrorLog("verify certificate chain exception: ", e);
		}
		return false;
	}
631845
public String validate(KeyStore keyStore, String keyAlias) throws CertificateException {
        String result = null;
        if (keyAlias != null) {
            try {
                validate(keyStore, keyStore.getCertificate(keyAlias));
            } catch (KeyStoreException kse) {
                logger.debug("", kse);
                throw new CertificateException("Unable to validate certificate" +
                        " for alias [" + keyAlias + "]: " + kse.getMessage(), kse);
            }
            result = keyAlias;
        }
	return result;
    }
381906
boolean verifySigned(File keystore, Certificate agentCertificate) {
        try {
            KeyStore store = KeyStore.getInstance("JKS");
            FileInputStream inputStream = new FileInputStream(keystore);
            store.load(inputStream, PASSWORD_AS_CHAR_ARRAY);
            IOUtils.closeQuietly(inputStream);
            KeyStore.PrivateKeyEntry intermediateEntry = (KeyStore.PrivateKeyEntry) store.getEntry("ca-intermediate",
                    new KeyStore.PasswordProtection(PASSWORD_AS_CHAR_ARRAY));
            Certificate intermediateCertificate = intermediateEntry.getCertificate();
            agentCertificate.verify(intermediateCertificate.getPublicKey());
            return true;
        } catch (Exception e) {
            return false;
        }
    }
20793
private void verifyNameChaining(X509Certificate cert)
        throws CertPathValidatorException
    {
        if (prevSubject != null) {

            String msg = "subject/issuer name chaining";
            if (debug != null)
                debug.println("---checking " + msg + "...");

            X500Principal currIssuer = cert.getIssuerX500Principal();

            // reject null or empty issuer DNs
            if (X500Name.asX500Name(currIssuer).isEmpty()) {
                throw new CertPathValidatorException
                    (msg + " check failed: " +
                     "empty/null issuer DN in certificate is invalid", null,
                     null, -1, PKIXReason.NAME_CHAINING);
            }

            if (!(currIssuer.equals(prevSubject))) {
                throw new CertPathValidatorException
                    (msg + " check failed", null, null, -1,
                     PKIXReason.NAME_CHAINING);
            }

            if (debug != null)
                debug.println(msg + " verified.");
        }
    }
13796
public void setCertificate() throws KeyStoreException, IOException, NoSuchAlgorithmException,
                    CertificateException, NoSuchPaddingException, InvalidKeyException,
                    IllegalBlockSizeException, BadPaddingException, UnrecoverableEntryException {
        KeyStore store = KeyStore.getInstance(this.keystore_type);
        InputStream inputStream=Thread.currentThread().getContextClassLoader().getResourceAsStream(this.keystore_path);
        if(inputStream == null)
            inputStream=new FileInputStream(this.keystore_path);
        store.load(inputStream, this.keystore_password);

        this.cipher = Cipher.getInstance(this.cipher_type);
        this.certificate = (X509Certificate) store.getCertificate(this.cert_alias);

        log.debug("certificate = " + this.certificate.toString());

        this.cipher.init(Cipher.ENCRYPT_MODE, this.certificate);
        this.encryptedToken = this.cipher.doFinal(this.auth_value.getBytes());

        KeyStore.PrivateKeyEntry privateKey = (KeyStore.PrivateKeyEntry) store.getEntry(
                        this.cert_alias, new KeyStore.PasswordProtection(this.cert_password));
        this.certPrivateKey = privateKey.getPrivateKey();

        this.valueSet=true;
    }
767227
void setCertificateToTruststore(X509Certificate[] chain) throws Exception {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "setCertificateToTruststore");

        try {

            WSKeyStore wsks = KeyStoreManager.getInstance().getKeyStore(tsCfgAlias);
            if (wsks == null)
                throw (new Exception("Keystore " + tsCfgAlias + " does not exist in the configuration."));
            if (wsks.getReadOnly()) {
                issueMessage("ssl.keystore.readonly.CWPKI0810I",
                             new Object[] { tsCfgAlias },
                             "The "
                                             + tsCfgAlias
                                             + " keystore is read only and the certificate will not be written to the keystore file.  Trust will be accepted only for this connection.");

            } else {
                for (int j = 0; j < chain.length; j++) {
                    String alias = chain[j].getSubjectDN().getName();
                    alias = alias.trim();

                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "Adding alias \"" + alias + "\" to truststore \"" + tsFile + "\".");
                    wsks.setCertificateEntry(alias, chain[chain.length - 1]);
                    String shaDigest = KeyStoreManager.getInstance().generateDigest("SHA-1", chain[chain.length - 1]);

                    issueMessage("ssl.signer.add.to.local.truststore.CWPKI0308I", new Object[] { alias, tsFile, shaDigest }, "CWPKI0308I: Adding signer alias \"" + alias
                                                                                                                             + "\" to local keystore \"" + tsFile
                                                                                                                             + "\" with the following SHA digest: " + shaDigest);

                    //Certificate is set on the truststore now clear the caches, if the file monitor is on let it handle the change.
                    String trigger = wsks.getTrigger();
                    if (!trigger.equalsIgnoreCase("disabled"))
                        clearSSLCachesAndResetDefault();
                }
            }
        } catch (Exception e) {
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Exception while trying to write certificate to the truststore. Exception is " + e.getMessage());
            throw e;
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "setCertificateToTruststore");
    }
220363
public void checkKeyStore() {
        if (sslContext != null)
            return; //nothing to check if using preconfigured context
        
        if (keyStoreInputStream == null &&
	    sslConfig.getKeyStorePath() == null) {
            throw new IllegalStateException("SSL doesn't have a valid keystore");
        }
        // if the keystore has been configured but there is no
        // truststore configured, use the keystore as the truststore
        if (trustStoreInputStream == null && sslConfig.getTrustStorePath() == null) {
            trustStoreInputStream = keyStoreInputStream;
            sslConfig.setTrustStorePath(sslConfig.getKeyStorePath());
            sslConfig.setTrustStoreType(sslConfig.getKeyStoreType());
            sslConfig.setTrustStoreProvider(sslConfig.getKeyStoreProvider());
            sslConfig.setTrustStorePassword(sslConfig.getKeyStorePassword());
            sslConfig.setTrustManagerFactoryAlgorithm(sslConfig.getKeyManagerFactoryAlgorithm());
        }

        // It's the same stream we cannot read it twice, so read it once in memory
        if (keyStoreInputStream != null && keyStoreInputStream == trustStoreInputStream) {
            try {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
		streamCopy(keyStoreInputStream, baos, null, false);
                keyStoreInputStream.close();
                keyStoreInputStream = new ByteArrayInputStream(baos.toByteArray());
                trustStoreInputStream = new ByteArrayInputStream(baos.toByteArray());
            } catch (Exception ex) {
                throw new IllegalStateException(ex);
            }
        }
    }
68994
boolean validateCertificate(byte[] certPEM) {

        if (certPEM == null) {
            return false;
        }

        try {

            X509Certificate certificate = getX509Certificate(certPEM);
            if (null == certificate) {
                throw new Exception("Certificate transformation returned null");
            }

            return validateCertificate(certificate);
        } catch (Exception e) {
            logger.error("Cannot validate certificate. Error is: " + e.getMessage() + "\r\nCertificate (PEM, hex): "
                    + DatatypeConverter.printHexBinary(certPEM));
            return false;
        }
    }
174417
public void invoke(X509Certificate cert, GSIConstants.CertificateType certType) throws CertPathValidatorException {
        if (!requireSigningPolicyCheck(certType)) {
            return;
        }
        X500Principal caPrincipal = cert.getIssuerX500Principal();
        SigningPolicy policy;
        try {
            policy = this.policyStore.getSigningPolicy(caPrincipal);
        } catch (CertStoreException e) {
            throw new CertPathValidatorException(e);
        }

        if (policy == null) {
            throw new CertPathValidatorException("No signing policy for " + cert.getIssuerDN());
        }

        boolean valid = policy.isValidSubject(cert.getSubjectX500Principal());

        if (!valid) {
            throw new CertPathValidatorException("Certificate " + cert.getSubjectDN()
                    + " violates signing policy for CA " + caPrincipal.getName());
        }
    }