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:info.fetter.logstashforwarder.protocol.LumberjackClient.java

public LumberjackClient(String keyStorePath, String server, int port, int timeout) throws IOException {
    this.server = server;
    this.port = port;

    try {/* w  ww.  j  ava 2  s. co  m*/
        if (keyStorePath == null) {
            throw new IOException("Key store not configured");
        }
        if (server == null) {
            throw new IOException("Server address not configured");
        }

        keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(keyStorePath), null);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(keyStore);

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

        SSLSocketFactory socketFactory = context.getSocketFactory();
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(server), port), timeout);
        socket.setSoTimeout(timeout);
        sslSocket = (SSLSocket) socketFactory.createSocket(socket, server, port, true);
        sslSocket.setUseClientMode(true);
        sslSocket.startHandshake();

        output = new DataOutputStream(new BufferedOutputStream(sslSocket.getOutputStream()));
        input = new DataInputStream(sslSocket.getInputStream());

        logger.info("Connected to " + server + ":" + port);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jboss.as.test.integration.logging.syslogserver.TLSSyslogServer.java

/**
 * Creates custom sslContext from keystore and truststore configured in
 *
 * @see org.productivity.java.syslog4j.server.impl.net.tcp.TCPNetSyslogServer#initialize()
 */// w w  w .j a v a2 s  . c o  m
@Override
public void initialize() throws SyslogRuntimeException {
    super.initialize();

    if (isBouncyCastleInstalled()) {
        removeBouncyCastle();
        addBouncyCastleOnShutdown = true;
    }

    final SSLTCPNetSyslogServerConfigIF config = (SSLTCPNetSyslogServerConfigIF) this.tcpNetSyslogServerConfig;

    try {
        final char[] keystorePwd = config.getKeyStorePassword().toCharArray();
        final KeyStore keystore = loadKeyStore(config.getKeyStore(), keystorePwd);
        final char[] truststorePassword = config.getTrustStorePassword().toCharArray();
        final KeyStore truststore = loadKeyStore(config.getTrustStore(), truststorePassword);

        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, keystorePwd);

        final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(truststore);

        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    } catch (Exception e) {
        LOGGER.error("Exception occurred during SSLContext for TLS syslog server initialization", e);
        throw new SyslogRuntimeException(e);
    }
}

From source file:com.vmware.photon.controller.common.auth.AuthOIDCClient.java

private IdmClient createIdmClient(String domainControllerFQDN, int domainControllerPort, String user,
        String password) throws AuthException {
    try {//from ww w  .  j  a v a  2 s.co m
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(certificateStore.getKeyStore());
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
        IdmClient idmClient = new IdmClient(domainControllerFQDN, domainControllerPort,
                new DefaultHostnameVerifier(), sslContext);

        com.vmware.identity.openidconnect.client.AccessToken accessToken = getTokenHandler()
                .getAdminServerAccessToken(user, password).getAccessToken();

        com.vmware.identity.rest.core.client.AccessToken restAccessToken = new com.vmware.identity.rest.core.client.AccessToken(
                accessToken.getValue(), com.vmware.identity.rest.core.client.AccessToken.Type.JWT);
        idmClient.setToken(restAccessToken);
        return idmClient;
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new AuthException("Failed to createIdmClient", e);
    }
}

From source file:com.microsoft.tfs.core.config.httpclient.internal.DefaultX509TrustManager.java

public DefaultX509TrustManager(final KeyStore keyStore)
        throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
    final TrustManagerFactory factory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    factory.init(keyStore);
    final TrustManager[] trustManagers = factory.getTrustManagers();

    if (trustManagers.length == 0) {
        throw new NoSuchAlgorithmException("No trust manager found"); //$NON-NLS-1$
    }/*from  w  ww .ja  va 2 s  . c o  m*/

    if (!(trustManagers[0] instanceof X509TrustManager)) {
        throw new NoSuchAlgorithmException("No X509 trust manager found"); //$NON-NLS-1$
    }

    standardTrustManager = (X509TrustManager) trustManagers[0];
}

From source file:com.netflix.spinnaker.orca.webhook.config.WebhookConfiguration.java

private X509TrustManager getTrustManager(KeyStore keyStore) {
    try {//  www  .j av a 2s .  co m
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        return (X509TrustManager) trustManagers[0];
    } catch (KeyStoreException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.adito.server.jetty.CustomJsseListener.java

protected SSLServerSocketFactory createFactory() throws Exception {
    if (KeyStoreManager.getInstance(KeyStoreManager.DEFAULT_KEY_STORE).isKeyStoreEmpty()) {
        throw new Exception(
                "The keystore does not contain any certificates. Please run the installation wizard (--install).");
    }//w w  w  .  j  a v  a  2  s . co  m
    KeyStore ks = KeyStoreManager.getInstance(KeyStoreManager.DEFAULT_KEY_STORE).getKeyStore();
    String pw = ContextHolder.getContext().getConfig()
            .retrieveProperty(new ContextKey("webServer.keystore.sslCertificate.password"));
    KeyManager[] kma = new KeyManager[] { new CustomKeyManager(pw) };
    TrustManager[] tma = null;
    if (trustManager == null) {
        TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tm.init(ks);
        tma = tm.getTrustManagers();
    } else {

        // LDP - Add the existing trust managers so that outgoing certificates are still trusted.
        TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tm.init(ks);

        tma = new TrustManager[tm.getTrustManagers().length + 1];
        for (int i = 0; i < tm.getTrustManagers().length; i++) {
            tma[i] = tm.getTrustManagers()[i];
        }
        tma[tma.length - 1] = trustManager;
    }
    SSLContext sslc = SSLContext.getInstance("SSL");
    sslc.init(kma, tma, SecureRandom.getInstance("SHA1PRNG"));
    SSLServerSocketFactory ssfc = sslc.getServerSocketFactory();
    if (log.isInfoEnabled())
        log.info("SSLServerSocketFactory=" + ssfc);
    initialised = true;
    return ssfc;
}

From source file:com.sslexplorer.server.jetty.CustomJsseListener.java

protected SSLServerSocketFactory createFactory() throws Exception {
    if (KeyStoreManager.getInstance(KeyStoreManager.DEFAULT_KEY_STORE).isKeyStoreEmpty()) {
        throw new Exception(
                "The keystore does not contain any certificates. Please run the installation wizard (--install).");
    }//  ww w .  ja v  a 2s  . c o  m
    KeyStore ks = KeyStoreManager.getInstance(KeyStoreManager.DEFAULT_KEY_STORE).getKeyStore();
    String pw = ContextHolder.getContext().getConfig()
            .retrieveProperty(new ContextKey("webServer.keystore.sslCertificate.password"));
    KeyManager[] kma = new KeyManager[] { new CustomKeyManager(pw) };
    TrustManager[] tma = null;
    if (trustManager == null) {
        TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tm.init(ks);
        tma = tm.getTrustManagers();
    } else {

        // LDP - Add the existing trust managers so that outgoing certificates are still trusted.
        TrustManagerFactory tm = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tm.init(ks);

        tma = new TrustManager[tm.getTrustManagers().length + 1];
        for (int i = 0; i < tm.getTrustManagers().length - 1; i++) {
            tma[i] = tm.getTrustManagers()[i];
        }
        tma[tma.length - 1] = trustManager;
    }
    SSLContext sslc = SSLContext.getInstance("SSL");
    sslc.init(kma, tma, SecureRandom.getInstance("SHA1PRNG"));
    SSLServerSocketFactory ssfc = sslc.getServerSocketFactory();
    if (log.isInfoEnabled())
        log.info("SSLServerSocketFactory=" + ssfc);
    initialised = true;
    return ssfc;
}

From source file:ddf.catalog.source.opensearch.SecureRemoteConnectionImpl.java

/**
 * Creates a new SSLSocketFactory from a truststore and keystore. This is used during SSL
 * communications with the server.// ww w . ja v a2s  .  com
 * 
 * @param trustStoreLoc
 *            File path to the truststore.
 * @param trustStorePass
 *            Password to the truststore.
 * @param keyStoreLoc
 *            File path to the keystore.
 * @param keyStorePass
 *            Password to the keystore.
 * @return new SSLSocketFactory instance containing the trust and key stores.
 * @throws KeyStoreException
 * @throws IOException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 * @throws KeyManagementException
 */
public SSLSocketFactory createSocket(String trustStoreLoc, String trustStorePass, String keyStoreLoc,
        String keyStorePass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    String methodName = "createSocket";
    LOGGER.debug("ENTERING: " + methodName);

    LOGGER.debug("trustStoreLoc = " + trustStoreLoc);
    FileInputStream trustFIS = new FileInputStream(trustStoreLoc);
    LOGGER.debug("keyStoreLoc = " + keyStoreLoc);
    FileInputStream keyFIS = new FileInputStream(keyStoreLoc);

    // truststore stuff
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        LOGGER.debug("Loading trustStore");
        trustStore.load(trustFIS, trustStorePass.toCharArray());
    } finally {
        IOUtils.closeQuietly(trustFIS);
    }

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    LOGGER.debug("trust manager factory initialized");

    // keystore stuff
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        LOGGER.debug("Loading keyStore");
        keyStore.load(keyFIS, keyStorePass.toCharArray());
    } finally {
        IOUtils.closeQuietly(keyFIS);
    }
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, keyStorePass.toCharArray());
    LOGGER.debug("key manager factory initialized");

    // ssl context
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    LOGGER.debug("EXITING: " + methodName);

    return sslCtx.getSocketFactory();
}

From source file:org.elasticsearch.hadoop.rest.commonshttp.SSLSocketFactory.java

private TrustManager[] loadTrustManagers() throws GeneralSecurityException, IOException {
    if (!StringUtils.hasText(trustStoreLocation)) {
        return null;
    }//from w w  w .  ja  v a  2 s  .c  o m

    char[] pass = (StringUtils.hasText(trustStorePass) ? trustStorePass.trim().toCharArray() : null);
    KeyStore keyStore = loadKeyStore(trustStoreLocation, pass);
    TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmFactory.init(keyStore);
    TrustManager[] tms = tmFactory.getTrustManagers();

    if (tms != null && trust != null) {
        // be defensive since the underlying impl might not give us a copy
        TrustManager[] clone = new TrustManager[tms.length];

        for (int i = 0; i < tms.length; i++) {
            TrustManager tm = tms[i];
            if (tm instanceof X509TrustManager) {
                tm = new TrustManagerDelegate((X509TrustManager) tm, trust);
            }
            clone[i] = tm;
        }
        tms = clone;
    }

    return tms;
}

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

private X509TrustManager getTrustManager(KeyStore trustStore) throws CertificateException {
    try {//from   w w  w  . j  a  va  2 s.co  m
        Enumeration<String> aliases = trustStore.aliases();
        if (aliases.hasMoreElements()) {
            TrustManagerFactory factory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            factory.init(trustStore);
            TrustManager[] permanentTrustManagers = factory.getTrustManagers();
            TrustManager permanentTrustManager = permanentTrustManagers[0];
            return (X509TrustManager) permanentTrustManager;
        }
    } catch (Exception e) {
        throw new CertificateException(Messages.StudioTrustManager_CantCreateTrustManager, e);
    }

    return null;
}