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:org.glite.slcs.httpclient.ssl.ExtendedProtocolSocketFactory.java

/**
 * Adds the given truststore to the existing default JSSE {@link TrustManager}.
 * /*  w w w .j a va 2s  . com*/
 * @param truststore The truststore to add to the list.
 * @return An array of {@link TrustManager}
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
private TrustManager[] createExtendedTrustManagers(KeyStore truststore)
        throws KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException {
    if (truststore == null) {
        throw new IllegalArgumentException("Truststore may not be null");
    }
    LOG.debug("Initializing TrustManager");
    // initialize with the JSSE default trustStore
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init((KeyStore) null);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    // extend the default TrustManager
    // LOG.debug("default JSSE TrustManager# " + trustmanagers.length);
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            LOG.debug("Installing the ExtendedTrustX509TrustManager");
            trustmanagers[i] = new ExtendedX509TrustManager(truststore, (X509TrustManager) trustmanagers[i]);
        }
    }
    return trustmanagers;
}

From source file:com.archivas.clienttools.arcutils.utils.net.GetCertsX509TrustManager.java

public void initStandardTrustManager(KeyStore keystore)
        throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException {
    TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    factory.init(keystore);
    TrustManager[] trustmanagers = factory.getTrustManagers();

    // Iterate over the returned trustmanagers, look for an instance of X509TrustManager.
    // If found, use that as our "default" trust manager.
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            if (standardTrustManager == null) {
                standardTrustManager = (X509TrustManager) trustmanagers[i];
            }/*from   w  w w.ja  va2 s .c  om*/
            // break;
            LOG.log(Level.FINER, "standardTrustManager=" + trustmanagers[i]);
        }
    }
}

From source file:org.apache.jmeter.util.JsseSSLManager.java

private SSLContext createContext() throws GeneralSecurityException {
    SSLContext context;/*from www.  j  a v a 2  s.co  m*/
    if (pro != null) {
        context = SSLContext.getInstance(DEFAULT_SSL_PROTOCOL, pro); // $NON-NLS-1$
    } else {
        context = SSLContext.getInstance(DEFAULT_SSL_PROTOCOL); // $NON-NLS-1$
    }
    KeyManagerFactory managerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    JmeterKeyStore keys = this.getKeyStore();
    managerFactory.init(null, defaultpw == null ? new char[] {} : defaultpw.toCharArray());
    KeyManager[] managers = managerFactory.getKeyManagers();
    KeyManager[] newManagers = new KeyManager[managers.length];

    log.debug(keys.getClass().toString());

    // Now wrap the default managers with our key manager
    for (int i = 0; i < managers.length; i++) {
        if (managers[i] instanceof X509KeyManager) {
            X509KeyManager manager = (X509KeyManager) managers[i];
            newManagers[i] = new WrappedX509KeyManager(manager, keys);
        } else {
            newManagers[i] = managers[i];
        }
    }

    // Get the default trust managers
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(this.getTrustStore());

    // Wrap the defaults in our custom trust manager
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new CustomX509TrustManager((X509TrustManager) trustmanagers[i]);
        }
    }
    context.init(newManagers, trustmanagers, this.rand);
    if (log.isDebugEnabled()) {
        String[] dCiphers = context.getSocketFactory().getDefaultCipherSuites();
        String[] sCiphers = context.getSocketFactory().getSupportedCipherSuites();
        int len = (dCiphers.length > sCiphers.length) ? dCiphers.length : sCiphers.length;
        for (int i = 0; i < len; i++) {
            if (i < dCiphers.length) {
                log.debug("Default Cipher: " + dCiphers[i]);
            }
            if (i < sCiphers.length) {
                log.debug("Supported Cipher: " + sCiphers[i]);
            }
        }
    }
    return context;
}

From source file:org.kuali.mobility.push.dao.PushDaoImpl.java

private SSLSocket openConnectionToAPNS(String host, int port, String key, String passphrase) {
    SSLSocket socket;/*from w  w  w  .  j av  a  2  s.  c  om*/
    try {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");

        //          keyStore.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray());
        //          keyStore.load(getClass().getResourceAsStream("/newcert.p12"), "strange word to use".toCharArray());
        //          keyStore.load(this.getClass().getClassLoader().getResourceAsStream("newcert.p12"), "strange word to use".toCharArray());

        // This works when built with Eclipse, but not when built from command line. 
        // Has to do with where the build system puts /resources/*.p12 file
        //          keyStore.load(this.getClass().getClassLoader().getResourceAsStream(key), "strange word to use".toCharArray());

        // Currently only works when read from the server's FS. Won't currently read from within eclipse project. 
        // Putting it in /opt/kme/push prevents naming conflicts. 
        keyStore.load(new FileInputStream("/opt/kme/push/newcert.p12"), "strange word to use".toCharArray());

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");
        keyManagerFactory.init(keyStore, "strange word to use".toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");
        trustManagerFactory.init(keyStore);
        SSLContext sslCtx = SSLContext.getInstance("TLS");
        sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
        SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
        socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
        socket.startHandshake();

        //Diagnostic output
        Enumeration e = keyStore.aliases();
        LOG.info(e.toString());
        while (e.hasMoreElements()) {
            LOG.info("Alias: " + e.nextElement().toString());
        }

        String not = (socket.isConnected()) ? "" : "NOT ";
        LOG.info("SSLSocket is " + not + "Connected");

        LOG.info("Connected to: " + socket.getInetAddress().getCanonicalHostName());
        LOG.info("Connected to: " + socket.getInetAddress().getHostAddress());

        String cs[] = socket.getEnabledCipherSuites();
        LOG.info("CipherSuites: " + Arrays.toString(cs));

        String ep[] = socket.getEnabledProtocols();
        LOG.info("Enabled Protocols: " + Arrays.toString(ep));

        LOG.info("Timeout: " + socket.getSoTimeout());
        LOG.info("Send Buffer Size: " + socket.getSendBufferSize());

        return socket;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.candlepin.client.CustomSSLProtocolSocketFactory.java

private SSLContext createCustomSSLContext() {
    try {/*from  w  w w. j a v  a  2  s.c om*/
        KeyManager[] keyManagers = null;
        // Generate key managers off of the identity certificates if
        // doing client auth.
        if (clientAuth) {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            String[] keyCert = FileUtil.readKeyAndCert(configuration.getConsumerIdentityFilePath());
            kmf.init(PemUtil.pemToKeyStore(keyCert[1], keyCert[0], "password"), "password".toCharArray());
            keyManagers = kmf.getKeyManagers();
        }
        /* and provide them for the SSLContext */
        SSLContext ctx = SSLContext.getInstance("TLS");
        if (configuration.isIgnoreTrustManagers()) {
            ctx.init(keyManagers, Utils.DUMMY_TRUST_MGRS, new SecureRandom());
        } else {
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            KeyStore ks2 = KeyStore.getInstance(KeyStore.getDefaultType());
            ks2.load(null, null);

            ks2.setCertificateEntry("candlepin", PemUtil.readCert("/etc/candlepin/certs/candlepin-ca.crt"));
            // ks2.load(
            // new FileInputStream(configuration.getKeyStoreFileLocation()),
            // passwd);
            tmf.init(ks2);
            ctx.init(keyManagers, tmf.getTrustManagers(), new SecureRandom());
        }

        return ctx;
    } catch (Exception e) {
        e.printStackTrace();
        throw new HttpClientError(e.getMessage());
    }
}

From source file:org.kuali.kra.s2s.service.impl.GrantsGovConnectorServiceImpl.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig/*from ww  w.  java2  s. c  o  m*/
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2SException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2SException {
    KeyStore keyStore = S2SCertificateReader.getKeyStore();
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        if (alias != null && mulitCampusEnabled) {
            KeyStore keyStoreAlias;
            keyStoreAlias = KeyStore.getInstance(JKS_TYPE);
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(alias, key, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
        } else {
            keyManagerFactory.init(keyStore, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray());
        }
        KeyManager[] km = keyManagerFactory.getKeyManagers();
        tlsConfig.setKeyManagers(km);
        KeyStore trustStore = S2SCertificateReader.getTrustStore();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();
        tlsConfig.setTrustManagers(tm);
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (UnrecoverableKeyException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (CertificateException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (IOException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:net.jradius.server.TCPListener.java

public void setConfiguration(ListenerConfigurationItem cfg, boolean noKeepAlive)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException,
        KeyManagementException, IOException {
    keepAlive = !noKeepAlive;/*  w ww.  jav  a  2  s  .c  om*/
    config = cfg;

    Map props = config.getProperties();

    String s = (String) props.get("port");
    if (s != null)
        port = new Integer(s).intValue();

    s = (String) props.get("backlog");
    if (s != null)
        backlog = new Integer(s).intValue();

    if (keepAlive) {
        s = (String) props.get("keepAlive");
        if (s != null)
            keepAlive = new Boolean(s).booleanValue();
    }

    String useSSL = (String) props.get("useSSL");
    String trustAll = (String) props.get("trustAll");

    if (requiresSSL || "true".equalsIgnoreCase(useSSL)) {
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        String keyManager = (String) props.get("keyManager");

        if (keyManager != null && keyManager.length() > 0) {
            try {
                KeyManager manager = (KeyManager) Configuration.getBean(keyManager);
                keyManagers = new KeyManager[] { manager };
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            String keystore = (String) props.get("keyStore");
            String keystoreType = (String) props.get("keyStoreType");
            String keystorePassword = (String) props.get("keyStorePassword");
            String keyPassword = (String) props.get("keyPassword");

            if (keystore != null) {
                if (keystoreType == null)
                    keystoreType = "pkcs12";

                KeyStore ks = KeyStore.getInstance(keystoreType);
                ks.load(new FileInputStream(keystore),
                        keystorePassword == null ? null : keystorePassword.toCharArray());

                KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
                kmf.init(ks, keyPassword == null ? null : keyPassword.toCharArray());
                keyManagers = kmf.getKeyManagers();
            }
        }

        String trustManager = (String) props.get("trustManager");

        if (trustManager != null && trustManager.length() > 0) {
            try {
                TrustManager manager = (TrustManager) Configuration.getBean(trustManager);
                trustManagers = new TrustManager[] { manager };
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("true".equalsIgnoreCase(trustAll)) {
            trustManagers = new TrustManager[] { new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) {

                }

                public void checkServerTrusted(X509Certificate[] chain, String authType) {

                }

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } };
        } else {
            String keystore = (String) props.get("caStore");
            String keystoreType = (String) props.get("caStoreType");
            String keystorePassword = (String) props.get("caStorePassword");

            if (keystore != null) {
                if (keystoreType == null)
                    keystoreType = "pkcs12";

                KeyStore caKeys = KeyStore.getInstance(keystoreType);
                caKeys.load(new FileInputStream(keystore),
                        keystorePassword == null ? null : keystorePassword.toCharArray());
                TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
                tmf.init(caKeys);
                trustManagers = tmf.getTrustManagers();
            }
        }

        SSLContext sslContext = SSLContext.getInstance("SSLv3");
        sslContext.init(keyManagers, trustManagers, null);

        ServerSocketFactory socketFactory = sslContext.getServerSocketFactory();
        SSLServerSocket sslServerSocket = (SSLServerSocket) socketFactory.createServerSocket(port, backlog);
        serverSocket = sslServerSocket;

        if (sslWantClientAuth)
            sslServerSocket.setWantClientAuth(true);

        if (sslNeedClientAuth)
            sslServerSocket.setNeedClientAuth(true);

        if (sslEnabledProtocols != null)
            sslServerSocket.setEnabledProtocols(sslEnabledProtocols);

        if (sslEnabledCiphers != null)
            sslServerSocket.setEnabledCipherSuites(sslEnabledCiphers);

        usingSSL = true;
    } else {
        serverSocket = new ServerSocket(port, backlog);
    }

    serverSocket.setReuseAddress(true);
    setActive(true);
}

From source file:org.kuali.coeus.propdev.impl.s2s.connect.S2SConnectorServiceBase.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig/*from  w w w.  ja  va  2 s.c om*/
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2sCommunicationException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2sCommunicationException {
    KeyStore keyStore = s2sCertificateReader.getKeyStore();
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        if (alias != null && mulitCampusEnabled) {
            KeyStore keyStoreAlias;
            keyStoreAlias = KeyStore.getInstance(s2sCertificateReader.getJksType());
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(
                    alias, key, s2SConfigurationService
                            .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        } else {
            keyManagerFactory.init(keyStore, s2SConfigurationService
                    .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        }
        KeyManager[] km = keyManagerFactory.getKeyManagers();
        tlsConfig.setKeyManagers(km);
        KeyStore trustStore = s2sCertificateReader.getTrustStore();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();
        tlsConfig.setTrustManagers(tm);
    } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | CertificateException
            | IOException e) {
        LOG.error(e.getMessage(), e);
        throw new S2sCommunicationException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java

private HttpsURLConnection openSecureConnection(URL url) throws Exception {

    InputStream keyStream = new FileInputStream(truststorePath);

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(keyStream, Optional.ofNullable(truststorePassword).orElse("").toCharArray());

    TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(
            Optional.ofNullable(truststoreAlgorithm).orElseGet(TrustManagerFactory::getDefaultAlgorithm));
    trustFactory.init(keystore);

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, trustFactory.getTrustManagers(), null);

    HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();

    httpsURLConnection.setSSLSocketFactory(context.getSocketFactory());

    httpsURLConnection.setHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }/*  w  ww  . j  a va  2s . co  m*/
    });

    return httpsURLConnection;
}