Example usage for java.security.cert X509Certificate checkValidity

List of usage examples for java.security.cert X509Certificate checkValidity

Introduction

In this page you can find the example usage for java.security.cert X509Certificate checkValidity.

Prototype

public abstract void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException;

Source Link

Document

Checks that the certificate is currently valid.

Usage

From source file:com.vmware.identity.interop.ldap.SslX509EqualityMatchVerificationCallback.java

@Override
public boolean isTrustedCertificate(X509Certificate cert) {
    boolean certValidationResult = false;
    String fingerprint = "";
    try {//from   ww  w.  j  ava2 s.c  o  m
        fingerprint = SslUtil.computeHexCertificateThumbprint(cert);
    } catch (Exception e) {
        log.info("Can not calculate thumbprint");
    }

    try {
        if (this.trustedCertificates == null || trustedCertificates.size() == 0) {
            log.error(String.format(
                    "Server SSL certificate verification failed for [Subject: %s] [SHA1 Fingerprint: %s]. Trusted certificates store is empty.",
                    cert.getSubjectX500Principal().getName(), fingerprint));
        } else {
            cert.checkValidity();

            if (trustedCertificates.contains(cert)) {
                certValidationResult = true;
            } else {
                log.error(String.format(
                        "Server SSL certificate verification failed for [Subject: %s] [SHA1 Fingerprint: %s].: No match found in the trusted certificates store.",
                        cert.getSubjectX500Principal().getName(), fingerprint));
            }
        }
    } catch (CertificateExpiredException | CertificateNotYetValidException e) {
        log.error(String.format(
                "Server SSL certificate verification failed for  [Subject: %s] [SHA1 Fingerprint: %s].",
                cert.getSubjectX500Principal().getName(), fingerprint), e);
    }
    return certValidationResult;
}

From source file:com.cordys.coe.util.cgc.ssl.AuthSSLX509TrustManager.java

/**
 * This method checks if the certificate can be trusted. If you do not want to accept the
 * certificate you need to throw an exception.
 *
 * @param   certificates  The certificates to check.
 * @param   sAuthType     The authentication type.
 *
 * @throws  CertificateException  In case the certificate should not be accepted.
 *//*  ww  w  .j a v a  2 s .c  o  m*/
public void checkClientTrusted(X509Certificate[] certificates, String sAuthType) throws CertificateException {
    if (m_xtmDefault != null) {
        if (certificates != null) {
            for (int c = 0; c < certificates.length; c++) {
                X509Certificate cert = certificates[c];

                if (LOG.isInfoEnabled()) {
                    LOG.info(" Client certificate " + (c + 1) + ":");
                    LOG.info("  Subject DN: " + cert.getSubjectDN());
                    LOG.info("  Signature Algorithm: " + cert.getSigAlgName());
                    LOG.info("  Valid from: " + cert.getNotBefore());
                    LOG.info("  Valid until: " + cert.getNotAfter());
                    LOG.info("  Issuer: " + cert.getIssuerDN());
                }

                try {
                    cert.checkValidity();
                } catch (CertificateExpiredException e) {
                    LOG.fatal("Client certificate " + cert.getSubjectDN() + " is expired.");
                } catch (CertificateNotYetValidException e) {
                    LOG.fatal("Client certificate " + cert.getSubjectDN() + " is not yet valid.");
                }
            }
        }

        // Call the super to do the actual checking.
        m_xtmDefault.checkClientTrusted(certificates, sAuthType);
    }
}

From source file:com.cordys.coe.util.cgc.ssl.AuthSSLX509TrustManager.java

/**
 * This method checks if the server certificate is trusted.
 *
 * @param   certificates  The list of certificates.
 * @param   sAuthType     The authentication type.
 *
 * @throws  CertificateException  DOCUMENTME
 *//*from   ww  w .java2s  .  c o m*/
public void checkServerTrusted(X509Certificate[] certificates, String sAuthType) throws CertificateException {
    if (m_xtmDefault != null) {
        if (certificates != null) {
            for (int c = 0; c < certificates.length; c++) {
                X509Certificate cert = certificates[c];

                if (LOG.isInfoEnabled()) {
                    LOG.info(" Server certificate " + (c + 1) + ":");
                    LOG.info("  Subject DN: " + cert.getSubjectDN());
                    LOG.info("  Signature Algorithm: " + cert.getSigAlgName());
                    LOG.info("  Valid from: " + cert.getNotBefore());
                    LOG.info("  Valid until: " + cert.getNotAfter());
                    LOG.info("  Issuer: " + cert.getIssuerDN());
                }

                try {
                    cert.checkValidity();
                } catch (CertificateExpiredException e) {
                    LOG.fatal("Server certificate " + cert.getSubjectDN() + " is expired.");
                } catch (CertificateNotYetValidException e) {
                    LOG.fatal("Server certificate " + cert.getSubjectDN() + " is not yet valid.");
                }
            }
        }

        // Call the super to do the actual checking.
        m_xtmDefault.checkServerTrusted(certificates, sAuthType);
    }
}

From source file:org.jenkins_ci.update_center.Main.java

private X509Certificate loadCertificate(CertificateFactory cf, File f)
        throws CertificateException, IOException {
    FileInputStream in = new FileInputStream(f);
    try {//  w w  w.  j av  a 2 s  .  co  m
        X509Certificate c = (X509Certificate) cf.generateCertificate(in);
        c.checkValidity();
        return c;
    } finally {
        in.close();
    }
}

From source file:org.apache.nifi.web.security.x509.X509AuthenticationFilter.java

@Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
    String principal;//from   w w  w. j  av a2s  .c o m

    // extract the cert
    X509Certificate certificate = certificateExtractor.extractClientCertificate(request);

    // ensure the cert was found
    if (certificate == null) {
        return null;
    }

    // extract the principal
    Object certificatePrincipal = principalExtractor.extractPrincipal(certificate);
    principal = DnUtils.formatProxyDn(certificatePrincipal.toString());

    try {
        // ensure the cert is valid
        certificate.checkValidity();
    } catch (CertificateExpiredException cee) {
        final String message = String.format("Client certificate for (%s) is expired.", principal);
        logger.info(message, cee);
        if (logger.isDebugEnabled()) {
            logger.debug("", cee);
        }
        return null;
    } catch (CertificateNotYetValidException cnyve) {
        final String message = String.format("Client certificate for (%s) is not yet valid.", principal);
        logger.info(message, cnyve);
        if (logger.isDebugEnabled()) {
            logger.debug("", cnyve);
        }
        return null;
    }

    // validate the certificate in question
    try {
        certificateValidator.validate(request);
    } catch (final Exception e) {
        logger.info(e.getMessage());
        if (logger.isDebugEnabled()) {
            logger.debug("", e);
        }
        return null;
    }

    // look for a proxied user
    if (StringUtils.isNotBlank(request.getHeader(PROXY_ENTITIES_CHAIN))) {
        principal = request.getHeader(PROXY_ENTITIES_CHAIN) + principal;
    }

    // log the request attempt - response details will be logged later
    logger.info(String.format("Attempting request for (%s) %s %s (source ip: %s)", principal,
            request.getMethod(), request.getRequestURL().toString(), request.getRemoteAddr()));

    return principal;
}

From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java

protected void checkValidity(X509Certificate cert) throws ProxyPathValidatorException {

    try {//from   ww w .j a v  a2  s .c  o m
        cert.checkValidity();
    } catch (CertificateExpiredException e) {
        throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, cert,
                "Certificate " + cert.getSubjectDN().getName() + " expired.");
    } catch (CertificateNotYetValidException e) {
        throw new ProxyPathValidatorException(ProxyPathValidatorException.FAILURE, cert,
                "Certificate " + cert.getSubjectDN().getName() + " not yet valid.");
    }
}

From source file:eu.stork.peps.auth.engine.core.impl.SignSW.java

/**
 * @param tokenSaml token SAML//from   ww w .  j a va 2s .  c o  m
 * @return the SAMLObject validated.
 * @throws SAMLEngineException error validate signature
 * @see eu.stork.peps.auth.engine.core.SAMLEngineSignI#validateSignature(org.opensaml.common.SignableSAMLObject)
 */
public final SAMLObject validateSignature(final SignableSAMLObject tokenSaml) throws SAMLEngineException {
    LOG.info("Start signature validation.");
    try {

        // Validate structure signature
        final SAMLSignatureProfileValidator sigProfValidator = new SAMLSignatureProfileValidator();
        try {
            // Indicates signature id conform to SAML Signature profile
            sigProfValidator.validate(tokenSaml.getSignature());
        } catch (ValidationException e) {
            LOG.error("ValidationException: signature isn't conform to SAML Signature profile.");
            throw new SAMLEngineException(e);
        }

        String aliasCert = null;
        X509Certificate certificate;

        final List<Credential> trustCred = new ArrayList<Credential>();

        for (final Enumeration<String> e = storkOwnKeyStore.aliases(); e.hasMoreElements();) {
            aliasCert = e.nextElement();
            final BasicX509Credential credential = new BasicX509Credential();
            certificate = (X509Certificate) storkOwnKeyStore.getCertificate(aliasCert);
            credential.setEntityCertificate(certificate);
            trustCred.add(credential);
        }

        final KeyInfo keyInfo = tokenSaml.getSignature().getKeyInfo();

        final org.opensaml.xml.signature.X509Certificate xmlCert = keyInfo.getX509Datas().get(0)
                .getX509Certificates().get(0);

        final CertificateFactory certFact = CertificateFactory.getInstance("X.509");
        final ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(xmlCert.getValue()));
        final X509Certificate cert = (X509Certificate) certFact.generateCertificate(bis);

        // Exist only one certificate
        final BasicX509Credential entityX509Cred = new BasicX509Credential();
        entityX509Cred.setEntityCertificate(cert);

        try {
            cert.checkValidity();
        } catch (CertificateExpiredException exp) {
            throw new SAMLEngineException("Certificate expired.");
        } catch (CertificateNotYetValidException exp) {
            throw new SAMLEngineException("Certificate not yet valid.");
        }

        /* A better use of PKI based validation but not wanted for STORK... 
          boolean trusted = false;
                
        for (final Enumeration<String> e = storkOwnKeyStore.aliases(); e.hasMoreElements();) 
         {
            aliasCert = e.nextElement();      
            certificate = (X509Certificate) storkOwnKeyStore.getCertificate(aliasCert);               
            try {
               cert.verify(certificate.getPublicKey());
               trusted = true;
               break;
            }
            catch (Exception ex) {
               //Do nothing - cert not trusted yet
            }
         }
                
        if (!trusted)
            throw new SAMLEngineException("Certificate is not trusted.");*/

        // Validate trust certificates
        final ExplicitX509CertificateTrustEvaluator chainTrustEvaluator = new ExplicitX509CertificateTrustEvaluator();

        if (!chainTrustEvaluator.validate(entityX509Cred, trustCred)) {
            throw new SAMLEngineException("Certificate is not trusted.");
        }
        final ExplicitKeyTrustEvaluator keyTrustEvaluator = new ExplicitKeyTrustEvaluator();

        if (!keyTrustEvaluator.validate(entityX509Cred, trustCred)) {
            throw new SAMLEngineException("Certificate is not trusted.");
        }

        // Validate signature
        final SignatureValidator sigValidator = new SignatureValidator(entityX509Cred);
        sigValidator.validate(tokenSaml.getSignature());

    } catch (ValidationException e) {
        LOG.error("ValidationException.");
        throw new SAMLEngineException(e);
    } catch (KeyStoreException e) {
        LOG.error("KeyStoreException.", e);
        throw new SAMLEngineException(e);
    } catch (GeneralSecurityException e) {
        LOG.error("GeneralSecurityException.", e);
        throw new SAMLEngineException(e);
    }
    LOG.info(tokenSaml.getSignatureReferenceID());
    LOG.info("Start signature validation - END.");
    return tokenSaml;
}

From source file:org.ejbca.core.ejb.ca.store.CertificateStoreSessionBean.java

@Override
public void authenticate(X509Certificate certificate, boolean requireAdminCertificateInDatabase)
        throws AuthenticationFailedException {
    // Check Validity
    try {//from   www .j a v a 2s.  co m
        certificate.checkValidity();
    } catch (Exception e) {
        String msg = intres.getLocalizedMessage("authentication.certexpired",
                CertTools.getNotAfter(certificate).toString());
        throw new AuthenticationFailedException(msg);
    }
    if (requireAdminCertificateInDatabase) {
        // TODO: Verify Signature on cert? Not really needed since it's one of ou certs in the database.
        // Check if certificate is revoked.
        boolean isRevoked = isRevoked(CertTools.getIssuerDN(certificate),
                CertTools.getSerialNumber(certificate));
        if (isRevoked) {
            // Certificate revoked or missing in the database
            String msg = intres.getLocalizedMessage("authentication.revokedormissing");
            throw new AuthenticationFailedException(msg);
        }
    } else {
        // TODO: We should check the certificate for CRL or OCSP tags and verify the certificate status
    }
}

From source file:com.openshift.restclient.ClientBuilder.java

private TrustManagerFactory initTrustManagerFactory(String alias, X509Certificate cert,
        Collection<X509Certificate> certs)
        throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    if (alias != null && (cert != null || certs != null)) {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        // need this load to initialize the key store, and allow for the subsequent set certificate entry
        ks.load(null, null);/*from  w  w w .j  a  va 2 s. co  m*/
        if (cert != null) {
            cert.checkValidity();
            ks.setCertificateEntry(alias, cert);
        }
        if (certs != null) {
            int i = 0;
            for (X509Certificate x509 : certs) {
                x509.checkValidity();
                ks.setCertificateEntry(alias + i, x509);
                i++;
            }
        }

        // testing has proven that you can only call init() once for a TrustManagerFactory wrt loading certs
        // from the KeyStore ... subsequent KeyStore.setCertificateEntry / TrustManagerFactory.init calls are 
        // ignored.
        // So if a specific cert is required to validate this connection's communication with the server, add it up front
        // in the ctor.
        trustManagerFactory.init(ks);
    } else {
        trustManagerFactory.init((KeyStore) null);
    }
    return trustManagerFactory;
}

From source file:org.syncany.plugins.webdav.WebdavTransferManager.java

private ConnectionSocketFactory initSsl() throws Exception {
    TrustStrategy trustStrategy = new TrustStrategy() {
        @Override/*from  www .  ja v  a2 s.  c om*/
        public boolean isTrusted(X509Certificate[] certificateChain, String authType)
                throws CertificateException {
            logger.log(Level.INFO, "WebDAV: isTrusted(" + certificateChain.toString() + ", " + authType + ")");

            try {
                // First check if already in trust store, if so; okay!
                X509Certificate serverCertificate = certificateChain[0];

                for (int i = 0; i < certificateChain.length; i++) {
                    X509Certificate certificate = certificateChain[i];

                    logger.log(Level.FINE,
                            "WebDAV: Checking certificate validity: " + certificate.getSubjectDN().toString());
                    logger.log(Level.FINEST, "WebDAV:              Full certificate: " + certificate);

                    // Check validity
                    try {
                        certificate.checkValidity();
                    } catch (CertificateException e) {
                        logger.log(Level.FINE, "WebDAV: Certificate is NOT valid.", e);
                        return false;
                    }

                    logger.log(Level.FINE, "WebDAV: Checking is VALID.");

                    // Certificate found; we trust this, okay!
                    if (inTrustStore(certificate)) {
                        logger.log(Level.FINE, "WebDAV: Certificate found in trust store.");
                        return true;
                    }

                    // Certificate is new; continue ...
                    else {
                        logger.log(Level.FINE, "WebDAV: Certificate NOT found in trust store.");
                    }
                }

                // We we reach this code, none of the CAs are known in the trust store
                // So we ask the user if he/she wants to add the server certificate to the trust store  
                UserInteractionListener userInteractionListener = getSettings().getUserInteractionListener();

                if (userInteractionListener == null) {
                    throw new RuntimeException("pluginListener cannot be null!");
                }

                boolean userTrustsCertificate = userInteractionListener.onUserConfirm(
                        "Unknown SSL/TLS certificate", formatCertificate(serverCertificate),
                        "Do you want to trust this certificate?");

                if (!userTrustsCertificate) {
                    logger.log(Level.INFO, "WebDAV: User does not trust certificate. ABORTING.");
                    throw new RuntimeException("User does not trust certificate. ABORTING.");
                }

                logger.log(Level.INFO, "WebDAV: User trusts certificate. Adding to trust store.");
                addToTrustStore(serverCertificate);

                return true;
            } catch (KeyStoreException e) {
                logger.log(Level.SEVERE, "WebDAV: Key store exception.", e);
                return false;
            }
        }

        private boolean inTrustStore(X509Certificate certificate) throws KeyStoreException {
            String certAlias = getCertificateAlias(certificate);
            return UserConfig.getUserTrustStore().containsAlias(certAlias);
        }

        private void addToTrustStore(X509Certificate certificate) throws KeyStoreException {
            String certAlias = getCertificateAlias(certificate);
            UserConfig.getUserTrustStore().setCertificateEntry(certAlias, certificate);

            hasNewCertificates = true;
        }

        private String getCertificateAlias(X509Certificate certificate) {
            return StringUtil.toHex(certificate.getSignature());
        }
    };

    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, trustStrategy).useTLS().build();

    return new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
}