Example usage for javax.net.ssl TrustManagerFactory init

List of usage examples for javax.net.ssl TrustManagerFactory init

Introduction

In this page you can find the example usage for javax.net.ssl TrustManagerFactory init.

Prototype

public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes this factory with a source of provider-specific trust material.

Usage

From source file:me.vertretungsplan.parser.BaseParser.java

private static X509TrustManager trustManagerFromKeystore(final KeyStore keystore)
        throws GeneralSecurityException {
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX", "SunJSSE");
    trustManagerFactory.init(keystore);

    final TrustManager[] tms = trustManagerFactory.getTrustManagers();

    for (final TrustManager tm : tms) {
        if (tm instanceof X509TrustManager) {
            return X509TrustManager.class.cast(tm);
        }//from www.ja v a  2 s  .  c  om
    }
    throw new IllegalStateException("Could not locate X509TrustManager!");
}

From source file:org.wildfly.test.integration.elytron.sasl.mgmt.ExternalMgmtSaslTestCase.java

/**
 * Get the trust manager for {@link #CLIENT_TRUSTSTORE_FILE}.
 *
 * @return the trust manager/*from   w w  w .  ja  va2 s .  c  o m*/
 */
private static X509TrustManager getTrustManager() throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(loadKeyStore(CLIENT_TRUSTSTORE_FILE));

    for (TrustManager current : trustManagerFactory.getTrustManagers()) {
        if (current instanceof X509TrustManager) {
            return (X509TrustManager) current;
        }
    }

    throw new IllegalStateException("Unable to obtain X509TrustManager.");
}

From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java

private static SSLContext sslContext() {
    final String property = SettingsManager.settings().ssl();
    if (property != null && !property.isEmpty() && !"null".equals(property)) {
        if ("trustanything".equals(property)) {
            try {
                return SSLContexts.custom().loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()),
                        new TrustStrategy() {
                            public boolean isTrusted(X509Certificate[] chain, String authType)
                                    throws CertificateException {
                                return true;
                            }/* w  ww  .ja v a2  s.  com*/
                        }).build();
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        } else {
            try {
                String location = property;
                location = location.equals("compatible")
                        ? "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt"
                        : location;
                File cachedPemFile = new File("./pemfile_cached");
                boolean remote = location.startsWith("https://") || location.startsWith("http://");
                if (remote && cachedPemFile.exists()
                        && (System.currentTimeMillis() - cachedPemFile.lastModified() < 48 * 60 * 60 * 1000)) {
                    location = cachedPemFile.getAbsolutePath();
                    remote = false;
                }
                String pemBlocks = null;
                if (remote) {
                    HttpURLConnection remotePemFile = (HttpURLConnection) StreamHandler
                            .defaultConnection(new URL(location));
                    remotePemFile.setRequestMethod("GET");
                    remotePemFile.connect();
                    pemBlocks = Util.toString(remotePemFile.getInputStream(), Util.charset(remotePemFile));
                    cachedPemFile.delete();
                    Files.write(Paths.get(cachedPemFile.getAbsolutePath()), pemBlocks.getBytes("utf-8"));
                } else {
                    pemBlocks = new String(Files.readAllBytes(Paths.get(new File(location).getAbsolutePath())),
                            "utf-8");
                }
                KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                keyStore.load(null);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                Matcher matcher = pemBlock.matcher(pemBlocks);
                boolean found = false;
                while (matcher.find()) {
                    String pemBlock = matcher.group(1).replaceAll("[\\n\\r]+", "");
                    ByteArrayInputStream byteStream = new ByteArrayInputStream(
                            Base64.getDecoder().decode(pemBlock));
                    java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) cf
                            .generateCertificate(byteStream);
                    String alias = cert.getSubjectX500Principal().getName("RFC2253");
                    if (alias != null && !keyStore.containsAlias(alias)) {
                        found = true;
                        keyStore.setCertificateEntry(alias, cert);
                    }
                }
                if (found) {
                    KeyManagerFactory keyManager = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    keyManager.init(keyStore, null);
                    TrustManagerFactory trustManager = TrustManagerFactory
                            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    trustManager.init(keyStore);
                    SSLContext context = SSLContext.getInstance("TLS");
                    context.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
                    return context;
                }
            } catch (Throwable t) {
                LogsServer.instance().exception(t);
            }
        }
    }
    return SSLContexts.createSystemDefault();
}

From source file:org.apache.juddi.v3.client.cryptor.TransportSecurityHelper.java

public static boolean applyTransportSecurity(BindingProvider webServicePort) {
    try {/*ww  w  .  j a va 2  s . com*/
        File currentdir = new File(".");
        String s = System.getProperty("javax.net.ssl.keyStore");
        String st = System.getProperty("javax.net.ssl.trustStore");
        log.info("Attempting to initialize keystore and truststore from " + s + " " + st);
        if (s == null) {
            log.warn("keystore isn't defined! " + s);
            return false;
        } else if (st == null) {
            log.warn("truststore isn't defined! " + s);
            return false;
        } else {
            File keystore = new File(s);
            if (keystore == null || !keystore.exists()) {
                log.warn("keystore doesn't exist! input was " + s + " working dir is "
                        + currentdir.getAbsolutePath());
                return false;
            }
            //File truststore =new File(System.getProperty("javax.net.ssl.trustStore"));
            String pwd = System.getProperty("javax.net.ssl.keyStorePassword");
            if (pwd == null) {
                log.warn("keystore password isn't defined!");
                return false;
            }

            File truststore = new File(st);
            if (truststore == null || !truststore.exists()) {
                log.warn("truststore doesn't exist! input was " + s + " working dir is "
                        + currentdir.getAbsolutePath());
                return false;
            }
            //File truststore =new File(System.getProperty("javax.net.ssl.trustStore"));
            String pwdt = System.getProperty("javax.net.ssl.trustStorePassword");
            if (pwdt == null) {
                log.warn("truststore password isn't defined!");
                return false;
            }

            if (keystore.exists()) {
                try {
                    log.info("Using keystore from " + keystore.getAbsolutePath() + " current dir is "
                            + currentdir.getAbsolutePath());

                    log.info("Using truststore from " + truststore.getAbsolutePath() + " current dir is "
                            + currentdir.getAbsolutePath());
                    //log.info("Using truststure from " + truststore.getAbsolutePath() + " current dir is " + currentdir.getAbsolutePath());
                    SSLContext sc = SSLContext.getInstance("SSLv3");

                    KeyManagerFactory kmf = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

                    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
                    ks.load(new FileInputStream(keystore), pwd.toCharArray());

                    kmf.init(ks, pwd.toCharArray());

                    String alg = TrustManagerFactory.getDefaultAlgorithm();
                    TrustManagerFactory tmFact = TrustManagerFactory.getInstance(alg);

                    FileInputStream fis = new FileInputStream(st);
                    KeyStore kst = KeyStore.getInstance("jks");
                    kst.load(fis, pwdt.toCharArray());
                    fis.close();

                    tmFact.init(kst);

                    TrustManager[] tms = tmFact.getTrustManagers();

                    sc.init(kmf.getKeyManagers(), null, null);
                    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                    ((BindingProvider) webServicePort).getRequestContext().put(
                            "com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory",
                            sc.getSocketFactory());
                    ((BindingProvider) webServicePort).getRequestContext().put(
                            "com.sun.xml.ws.transport.https.client.SSLSocketFactory", sc.getSocketFactory());
                    return true;
                } catch (Exception ex) {
                    log.warn("unable to establish ssl settings", ex);
                }
            }
        }
        return false;
    } catch (Exception x) {
        log.error("unexpected error", x);
    }
    return false;
}

From source file:org.asynchttpclient.test.TestUtils.java

private static TrustManager[] createTrustManagers() throws GeneralSecurityException, IOException {
    KeyStore ks = KeyStore.getInstance("JKS");
    try (InputStream keyStoreStream = TestUtils.class.getClassLoader()
            .getResourceAsStream("ssltest-keystore.jks")) {
        char[] keyStorePassword = "changeit".toCharArray();
        ks.load(keyStoreStream, keyStorePassword);
    }//from  w w  w.jav  a2 s .  c o m
    assert (ks.size() > 0);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    return tmf.getTrustManagers();
}

From source file:org.wso2.carbon.identity.application.authentication.endpoint.util.MutualSSLManager.java

/**
 * Create basic SSL connection factory//w w  w  .j a  va2 s . c  o m
 *
 * @throws AuthenticationException
 */
public static void initMutualSSLConnection(boolean hostNameVerificationEnabled) throws AuthenticationException {

    try {
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(keyManagerType);
        keyManagerFactory.init(keyStore, keyStorePassword);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(trustManagerType);
        trustManagerFactory.init(trustStore);

        // Create and initialize SSLContext for HTTPS communication
        SSLContext sslContext = SSLContext.getInstance(protocol);

        if (hostNameVerificationEnabled) {
            sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            sslSocketFactory = sslContext.getSocketFactory();

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification enabled");
            }
        } else {
            // All the code below is to overcome host name verification failure we get in certificate
            // validation due to self signed certificate.

            // Create empty HostnameVerifier
            HostnameVerifier hv = new HostnameVerifier() {
                @Override
                public boolean verify(String urlHostName, SSLSession session) {

                    return true;
                }
            };

            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {

                    return new java.security.cert.X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                    */
                }

                @Override
                public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
                    /*
                         skipped implementation
                     */
                }
            } };

            sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts,
                    new java.security.SecureRandom());

            if (log.isDebugEnabled()) {
                log.debug("SSL Context is initialized with trust manager for excluding certificate validation");
            }
            SSLContext.setDefault(sslContext);
            sslSocketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultHostnameVerifier(hv);

            if (log.isDebugEnabled()) {
                log.debug("Mutual SSL Client initialized with Hostname Verification disabled");
            }
        }
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
            | KeyManagementException e) {
        throw new AuthenticationException("Error while trying to load Trust Store.", e);
    }
}

From source file:gov.va.med.imaging.proxy.ssl.AuthSSLProtocolSocketFactory.java

private static TrustManager[] createTrustManagers(final KeyStore keystore)
        throws KeyStoreException, NoSuchAlgorithmException {
    if (keystore == null)
        throw new IllegalArgumentException("Keystore may not be null");

    Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("Initializing trust manager");
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new AuthSSLX509TrustManager((X509TrustManager) trustmanagers[i]);
        }// www  .  j a  v  a 2 s .c  o m
    }
    return trustmanagers;
}

From source file:org.exoplatform.services.videocall.AuthService.java

protected static TrustManager[] getTrustManagers(InputStream trustStoreFile, String trustStorePassword)
        throws Exception {
    CertificateFactory certificateFactory = null;
    try {/*from  w  w w.j a  va  2  s .  c o  m*/
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not initialize the certificate " + e.getMessage());
        }
    }

    Certificate caCert = null;
    try {
        caCert = certificateFactory.generateCertificate(trustStoreFile);
    } catch (CertificateException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Bad key or certificate in " + trustStoreFile, e.getMessage());
        }
    }

    KeyStore trustStore = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
    } catch (KeyStoreException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Java implementation cannot manipulate " + KeyStore.getDefaultType() + " keystores");
        }
    } catch (NoSuchAlgorithmException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not initialize truststore ", e);
        }
    } catch (CertificateException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not initialize truststore ", e);
        }
    } catch (IOException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Could not initialize truststore ", e);
        }
    }

    try {
        trustStore.setCertificateEntry("CA", caCert);
    } catch (KeyStoreException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error(trustStoreFile + " cannot be used as a CA", e);
        }
    }

    TrustManagerFactory tmf = null;
    try {
        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
    } catch (NoSuchAlgorithmException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Java implementation cannot manipulate " + KeyStore.getDefaultType() + " trusts", e);
        }
    } catch (KeyStoreException e) {
        LOG.error("Java implementation cannot manipulate " + KeyStore.getDefaultType() + " trusts", e);
    }
    return tmf.getTrustManagers();
}

From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java

public static HttpClient getHttpsClient(Certificate[] sslCertificate) {
    DefaultHttpClient httpClient;/*from  w  ww  .  j  ava  2  s  .co m*/

    httpClient = new DefaultHttpClient();
    try {
        TrustManagerFactory tf = TrustManagerFactory.getInstance("X509");
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null);
        for (int i = 0; i < sslCertificate.length; i++) {
            ks.setCertificateEntry("StartCom" + i, sslCertificate[i]);
        }

        tf.init(ks);
        TrustManager[] tm = tf.getTrustManagers();

        SSLContext sslCon = SSLContext.getInstance("SSL");
        sslCon.init(null, tm, new SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(ks);
        Scheme sch = new Scheme("https", 443, socketFactory);

        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException | UnrecoverableKeyException ex) {
        Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
    }

    return httpClient;
}

From source file:com.thejoshwa.ultrasonic.androidapp.service.ssl.SSLSocketFactory.java

private static SSLContext createSSLContext(String algorithm, final KeyStore keystore,
        final String keystorePassword, final KeyStore truststore, final SecureRandom random,
        final TrustStrategy trustStrategy)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    if (algorithm == null) {
        algorithm = TLS;/*from ww  w.  j a v a2s .c  o  m*/
    }
    KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmfactory.init(keystore, keystorePassword != null ? keystorePassword.toCharArray() : null);
    KeyManager[] keymanagers = kmfactory.getKeyManagers();
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    if (trustmanagers != null && trustStrategy != null) {
        for (int i = 0; i < trustmanagers.length; i++) {
            TrustManager tm = trustmanagers[i];
            if (tm instanceof X509TrustManager) {
                trustmanagers[i] = new TrustManagerDecorator((X509TrustManager) tm, trustStrategy);
            }
        }
    }

    SSLContext sslcontext = SSLContext.getInstance(algorithm);
    sslcontext.init(keymanagers, trustmanagers, random);
    return sslcontext;
}