Example usage for java.security.cert CertificateException CertificateException

List of usage examples for java.security.cert CertificateException CertificateException

Introduction

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

Prototype

public CertificateException(Throwable cause) 

Source Link

Document

Creates a CertificateException with the specified cause and a detail message of (cause==null ?

Usage

From source file:com.fine47.http.SecureSocketFactory.java

private SecureSocketFactory(String factoryId, KeyStore store, String alias) throws CertificateException,
        NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(store);

    // Loading the CA certificate from store.
    Certificate rootca = store.getCertificate(alias);

    // Turn it to X509 format.
    InputStream is = new ByteArrayInputStream(rootca.getEncoded());
    X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is);
    ActivityHttpClient.silentCloseInputStream(is);

    if (null == x509ca) {
        throw new CertificateException("Found expired SSL certificate in this store: " + factoryId);
    }//from   w  w  w.ja  v a  2s .c  o  m

    // Check the CA's validity.
    x509ca.checkValidity();

    // Accepted CA is only the one installed in the store.
    acceptedIssuers = new X509Certificate[] { x509ca };

    // Get the public key.
    publicKey = rootca.getPublicKey();

    sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, new TrustManager[] { new X509TrustManager() {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            Exception error = null;

            if (null == chain || 0 == chain.length) {
                error = new CertificateException("Certificate chain is invalid");
            } else if (null == authType || 0 == authType.length()) {
                error = new CertificateException("Authentication type is invalid");
            } else
                try {
                    for (X509Certificate cert : chain) {
                        if (ActivityHttpClient.isDebugging()) {
                            Log.d(ActivityHttpClient.LOG_TAG, "Server Certificate Details:");
                            Log.d(ActivityHttpClient.LOG_TAG, "---------------------------");
                            Log.d(ActivityHttpClient.LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "Serial Number: " + cert.getSerialNumber());
                            Log.d(ActivityHttpClient.LOG_TAG, "Version: " + cert.getVersion());
                            Log.d(ActivityHttpClient.LOG_TAG, "Not before: " + cert.getNotBefore().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "Not after: " + cert.getNotAfter().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "---------------------------");
                        }

                        // Make sure that it hasn't expired.
                        cert.checkValidity();

                        // Verify the certificate's chain.
                        cert.verify(publicKey);
                    }
                } catch (InvalidKeyException ex) {
                    error = ex;
                } catch (NoSuchAlgorithmException ex) {
                    error = ex;
                } catch (NoSuchProviderException ex) {
                    error = ex;
                } catch (SignatureException ex) {
                    error = ex;
                }
            if (null != error && ActivityHttpClient.isDebugging()) {
                Log.e(ActivityHttpClient.LOG_TAG, "Error while setting up a secure socket factory.", error);
                throw new CertificateException(error);
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return acceptedIssuers;
        }
    } }, null);

    setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
}

From source file:org.shelloid.common.ShelloidUtil.java

@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
    for (X509Certificate cert : certs) {
        if (cert.getIssuerDN().getName().contains("Shelloid")) {
            this.certs.add(cert);
        } else {//  w ww.  ja  va2  s  .com
            throw new CertificateException("Certificate DN doesn't contains shelloid");
        }
    }
}

From source file:se.inera.axel.shs.broker.validation.certificate.CertificateExtractorImpl.java

private String extractSenderFromPrincipal(String principalName) throws CertificateException {
    log.debug("principalName: {}", principalName);

    if (pattern == null) {
        log.error(/*from   w w w  .ja  v  a 2 s . c  om*/
                "Property shs.senderCertificateValidator.senderPatternInCertificate must not be empty because sender validation is enabled (shs.senderCertificateValidator.enabled=true).");
        return null;
    }

    final Matcher matcher = pattern.matcher(principalName);

    if (matcher.find()) {
        String sender = matcher.group(1);
        log.debug("Found sender id {}", sender);

        if (sender.startsWith("#")) {
            try {
                sender = convertFromHexToString(sender.substring(5));
            } catch (Exception e) {
                String msg = "convertFromHexToString failed for sender[" + sender + "]";
                log.error(msg, e);
                throw new CertificateException(msg);
            }
        }
        return sender;
    } else {
        log.error("No sender found in certificate. \npattern ... " + pattern.toString() + "\nprincipalName ... "
                + principalName);
        throw new CertificateException("No sender found in certificate: " + principalName);
    }
}

From source file:com.vmware.bdd.cli.http.DefaultTrustManager.java

@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    String errorMsg = "";
    InputStream in = null;/* ww  w.  j a v  a2  s. co  m*/
    OutputStream out = null;

    // load key store file
    try {
        char[] pwd = cliProperties.readKeyStorePwd();
        File file = new File(KEY_STORE_FILE);

        if (file.exists() && file.isFile()) {
            keyStore.load(new FileInputStream(file), pwd);
        } else {
            //init an empty keystore
            keyStore.load(null, pwd);
        }

        // show certificate informations
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        String md5Fingerprint = "";
        String sha1Fingerprint = "";
        SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy/MM/dd");
        for (int i = 0; i < chain.length; i++) {
            X509Certificate cert = chain[i];
            sha1.update(cert.getEncoded());
            md5.update(cert.getEncoded());
            md5Fingerprint = ByteArrayUtils.byteArrayToHexString(md5.digest());
            sha1Fingerprint = ByteArrayUtils.byteArrayToHexString(sha1.digest());
            if (keyStore.getCertificate(md5Fingerprint) != null) {
                if (i == chain.length - 1) {
                    return;
                } else {
                    continue;
                }
            }
            System.out.println();
            System.out.println("Server Certificate");
            System.out.println("================================================================");
            System.out.println("Subject:  " + cert.getSubjectDN());
            System.out.println("Issuer:  " + cert.getIssuerDN());
            System.out.println("SHA Fingerprint:  " + sha1Fingerprint);
            System.out.println("MD5 Fingerprint:  " + md5Fingerprint);
            System.out.println("Issued on:  " + dateFormate.format(cert.getNotBefore()));
            System.out.println("Expires on:  " + dateFormate.format(cert.getNotAfter()));
            System.out.println("Signature:  " + cert.getSignature());
            System.out.println();
            if (checkExpired(cert.getNotBefore(), cert.getNotAfter())) {
                throw new CertificateException("The security certificate has expired.");
            }
            ConsoleReader reader = new ConsoleReader();
            // Set prompt message
            reader.setPrompt(Constants.PARAM_PROMPT_ADD_CERTIFICATE_MESSAGE);
            // Read user input
            String readMsg;
            if (RunWayConfig.getRunType().equals(RunWayConfig.RunType.MANUAL)) {
                readMsg = reader.readLine().trim();
            } else {
                readMsg = "yes";
            }
            if ("yes".equalsIgnoreCase(readMsg) || "y".equalsIgnoreCase(readMsg)) {
                {
                    // add new certificate into key store file.
                    keyStore.setCertificateEntry(md5Fingerprint, cert);
                    out = new FileOutputStream(KEY_STORE_FILE);
                    keyStore.store(out, pwd);
                    CommonUtil.setOwnerOnlyReadWrite(KEY_STORE_FILE);
                    // save keystore password
                    cliProperties.saveKeyStorePwd(pwd);
                }
            } else {
                if (i == chain.length - 1) {
                    throw new CertificateException("Could not find a valid certificate in the keystore.");
                } else {
                    continue;
                }
            }
        }
    } catch (FileNotFoundException e) {
        errorMsg = "Cannot find the keystore file: " + e.getMessage();
    } catch (NoSuchAlgorithmException e) {
        errorMsg = "SSL Algorithm not supported: " + e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        errorMsg = "IO error: " + e.getMessage();
    } catch (KeyStoreException e) {
        errorMsg = "Keystore error: " + e.getMessage();
    } catch (ConfigurationException e) {
        errorMsg = "cli.properties access error: " + e.getMessage();
    } finally {
        if (!CommandsUtils.isBlank(errorMsg)) {
            System.out.println(errorMsg);
            logger.error(errorMsg);
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logger.warn("Input stream of serengeti.keystore close failed.");
            }
        }
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                logger.warn("Output stream of serengeti.keystore close failed.");
            }
        }
    }
}

From source file:com.subgraph.vega.internal.http.proxy.ssl.CertificateCreator.java

private KeyPairGenerator createKeyGenerator() throws CertificateException {
    try {/*w w w  .  ja  v  a  2s  . c o m*/
        final KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
        kpg.initialize(1024);
        return kpg;
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateException("Failed to create RSA key pair generator." + e.getMessage());
    }
}

From source file:ee.ria.xroad.common.request.ManagementRequestClient.java

private void createCentralHttpClient() throws Exception {
    log.trace("createCentralHttpClient()");

    TrustManager tm = new X509TrustManager() {
        @Override//  ww  w.  j  ava2 s.  c  o  m
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            if (chain.length == 0) {
                throw new CertificateException("Central server did not send TLS certificate");
            }

            X509Certificate centralServerSslCert = null;

            try {
                centralServerSslCert = GlobalConf.getCentralServerSslCertificate();
            } catch (Exception e) {
                throw new CertificateException("Could not get central server TLS certificate from global conf",
                        e);
            }

            if (centralServerSslCert == null) {
                throw new CertificateException("Central server TLS certificate is not in global conf");
            }

            if (!centralServerSslCert.equals(chain[0])) {
                throw new CertificateException("Central server TLS certificate does not match in global conf");
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    centralHttpClient = createHttpClient(null, tm);
}

From source file:org.projectforge.business.ldap.MyTrustManager.java

public void checkServerTrusted(final X509Certificate[] chain, final String authType)
        throws CertificateException {
    if (certificate != null) {
        try {/*from w  ww  . ja va 2s  .co  m*/
            chain[0].verify(certificate.getPublicKey());
            for (final X509Certificate cert : chain) {
                // Verifing by public key
                cert.checkValidity();
            }
        } catch (final InvalidKeyException ex) {
            throw new CertificateException(ex);
        } catch (final NoSuchAlgorithmException ex) {
            throw new CertificateException(ex);
        } catch (final NoSuchProviderException ex) {
            throw new CertificateException(ex);
        } catch (final SignatureException ex) {
            throw new CertificateException(ex);
        }
    } else {
        trustManager.checkServerTrusted(chain, authType);
    }
}

From source file:com.sk89q.mclauncher.security.X509KeyStore.java

/**
 * Check if a server certificate chain is trusted.
 *///from www.  ja  va  2 s .  c om
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    for (X509Certificate cert : chain) {
        cert.checkValidity();
        if (cert.hasUnsupportedCriticalExtension()) {
            throw new CertificateException("Unsupported critical extension found");
        }
    }

    try {
        verify(chain);
    } catch (CertificateVerificationException e) {
        throw new CertificateException("Verification error: " + e.getMessage(), e);
    } catch (CertPathBuilderException e) {
        throw new CertificateException(e.getMessage(), e);
    }
}

From source file:com.amazon.speech.speechlet.authentication.SpeechletRequestSignatureVerifier.java

/**
 * Retrieves the certificate from the specified URL and confirms that the certificate is valid.
 *
 * @param signingCertificateChainUrl//from  w w  w  .ja v a  2 s.c  om
 *            the URL to retrieve the certificate chain from
 * @return the certificate at the specified URL, if the certificate is valid
 * @throws CertificateException
 *             if the certificate cannot be retrieve or is invalid
 */
public static X509Certificate retrieveAndVerifyCertificateChain(final String signingCertificateChainUrl)
        throws CertificateException {
    try (InputStream in = getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openStream()) {
        CertificateFactory certificateFactory = CertificateFactory.getInstance(Sdk.SIGNATURE_CERTIFICATE_TYPE);
        @SuppressWarnings("unchecked")
        Collection<X509Certificate> certificateChain = (Collection<X509Certificate>) certificateFactory
                .generateCertificates(in);
        /*
         * check the before/after dates on the certificate date to confirm that it is valid on
         * the current date
         */
        X509Certificate signingCertificate = certificateChain.iterator().next();
        signingCertificate.checkValidity();

        // check the certificate chain
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);

        X509TrustManager x509TrustManager = null;
        for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
            if (trustManager instanceof X509TrustManager) {
                x509TrustManager = (X509TrustManager) trustManager;
            }
        }

        if (x509TrustManager == null) {
            throw new IllegalStateException(
                    "No X509 TrustManager available. Unable to check certificate chain");
        } else {
            x509TrustManager.checkServerTrusted(
                    certificateChain.toArray(new X509Certificate[certificateChain.size()]),
                    Sdk.SIGNATURE_KEY_TYPE);
        }

        /*
         * verify Echo API's hostname is specified as one of subject alternative names on the
         * signing certificate
         */
        if (!subjectAlernativeNameListContainsEchoSdkDomainName(
                signingCertificate.getSubjectAlternativeNames())) {
            throw new CertificateException("The provided certificate is not valid for the Echo SDK");
        }

        return signingCertificate;
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException ex) {
        throw new CertificateException("Unable to verify certificate at URL: " + signingCertificateChainUrl,
                ex);
    }
}

From source file:org.apache.directory.studio.connection.core.io.StudioTrustManager.java

/**
 * {@inheritDoc}/*from www .j a v a 2 s  .  co  m*/
 */
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    // check permanent trusted certificates, return on success
    try {
        X509TrustManager permanentTrustManager = getPermanentTrustManager();
        if (permanentTrustManager != null) {
            permanentTrustManager.checkServerTrusted(chain, authType);
            return;
        }
    } catch (CertificateException ce) {
    }

    // check temporary trusted certificates, return on success
    try {
        X509TrustManager sessionTrustManager = getSessionTrustManager();
        if (sessionTrustManager != null) {
            sessionTrustManager.checkServerTrusted(chain, authType);
            return;
        }
    } catch (CertificateException ce) {
    }

    // below here no manually trusted certificate (either permanent or temporary) matched
    List<ICertificateHandler.FailCause> failCauses = new ArrayList<ICertificateHandler.FailCause>();

    // perform trust check of JVM trust manager
    try {
        jvmTrustManager.checkServerTrusted(chain, authType);
    } catch (CertificateException ce) {
        if (ce instanceof CertificateExpiredException) {
            failCauses.add(FailCause.CertificateExpired);
        } else if (ce instanceof CertificateNotYetValidException) {
            failCauses.add(FailCause.CertificateNotYetValid);
        } else {
            X500Principal issuerX500Principal = chain[0].getIssuerX500Principal();
            X500Principal subjectX500Principal = chain[0].getSubjectX500Principal();
            if (issuerX500Principal.equals(subjectX500Principal)) {
                failCauses.add(FailCause.SelfSignedCertificate);
            } else {
                failCauses.add(FailCause.NoValidCertificationPath);
            }

            try {
                chain[0].checkValidity();
            } catch (CertificateException ve) {
                if (ve instanceof CertificateExpiredException) {
                    failCauses.add(FailCause.CertificateExpired);
                } else if (ve instanceof CertificateNotYetValidException) {
                    failCauses.add(FailCause.CertificateNotYetValid);
                }
            }
        }
    }

    // perform host name verification
    try {
        BrowserCompatHostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();
        hostnameVerifier.verify(host, chain[0]);
    } catch (SSLException ce) {
        failCauses.add(FailCause.HostnameVerificationFailed);
    }

    if (!failCauses.isEmpty()) {
        // either trust check or host name verification
        // ask for confirmation
        ICertificateHandler ch = ConnectionCorePlugin.getDefault().getCertificateHandler();
        ICertificateHandler.TrustLevel trustLevel = ch.verifyTrustLevel(host, chain, failCauses);
        switch (trustLevel) {
        case Permanent:
            ConnectionCorePlugin.getDefault().getPermanentTrustStoreManager().addCertificate(chain[0]);
            break;
        case Session:
            ConnectionCorePlugin.getDefault().getSessionTrustStoreManager().addCertificate(chain[0]);
            break;
        case Not:
            throw new CertificateException(Messages.error__untrusted_certificate);
        }
    }
}