Example usage for javax.net.ssl TrustManagerFactory getInstance

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

Introduction

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

Prototype

public static final TrustManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a TrustManagerFactory object that acts as a factory for trust managers.

Usage

From source file:io.fabric8.utils.cxf.WebClients.java

public static void configureCaCert(WebClient webClient, String caCertData, File caCertFile) {
    try {//from w  w  w .j a  v a2 s  .co m
        KeyStore trustStore = createTrustStore(caCertData, caCertFile);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

        HTTPConduit conduit = WebClient.getConfig(webClient).getHttpConduit();

        TLSClientParameters params = conduit.getTlsClientParameters();

        if (params == null) {
            params = new TLSClientParameters();
            conduit.setTlsClientParameters(params);
        }

        TrustManager[] existingTrustManagers = params.getTrustManagers();

        if (!ArrayUtils.isEmpty(existingTrustManagers)) {
            trustManagers = (TrustManager[]) ArrayUtils.addAll(existingTrustManagers, trustManagers);
        }

        params.setTrustManagers(trustManagers);
    } catch (Exception e) {
        LOG.error("Could not create trust manager for " + caCertFile, e);
    }
}

From source file:de.betterform.connector.http.ssl.BetterFORMTrustManager.java

private TrustManager[] getCustomX509TrustManagers(final URL url, final String password)
        throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException,
        UnrecoverableKeyException {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    if (url == null) {
        throw new IllegalArgumentException("BetterFORMTrustManager: Keystore url may not be null");
    }//from w w w  . jav a  2s .  c o  m

    LOGGER.debug("BetterFORMTrustManager: initializing custom key store");
    KeyStore customKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = null;
    try {
        is = url.openStream();
        customKeystore.load(is, password != null ? password.toCharArray() : null);
    } finally {
        if (is != null)
            is.close();
    }

    trustManagerFactory.init(customKeystore);

    TrustManager[] customX509TrustManagers = trustManagerFactory.getTrustManagers();
    for (int i = 0; i < customX509TrustManagers.length; i++) {
        if (customX509TrustManagers[i] instanceof X509TrustManager) {
            customX509TrustManagers[i] = new AuthSSLX509TrustManager(
                    (X509TrustManager) customX509TrustManagers[i]);
        }
    }
    return customX509TrustManagers;
}

From source file:org.apache.nifi.framework.security.util.SslContextFactory.java

public static SSLContext createSslContext(final NiFiProperties props, final boolean strict)
        throws SslContextCreationException {

    final boolean hasKeystoreProperties = hasKeystoreProperties(props);
    if (hasKeystoreProperties == false) {
        if (strict) {
            throw new SslContextCreationException(
                    "SSL context cannot be created because keystore properties have not been configured.");
        } else {/*from   w  w  w . j a v a  2 s  .co m*/
            return null;
        }
    } else if (props.getNeedClientAuth() && hasTruststoreProperties(props) == false) {
        throw new SslContextCreationException(
                "Need client auth is set to 'true', but no truststore properties are configured.");
    }

    try {
        // prepare the trust store
        final KeyStore trustStore;
        if (hasTruststoreProperties(props)) {
            trustStore = KeyStoreUtils
                    .getTrustStore(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE));
            try (final InputStream trustStoreStream = new FileInputStream(
                    props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE))) {
                trustStore.load(trustStoreStream,
                        props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD).toCharArray());
            }
        } else {
            trustStore = null;
        }
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        // prepare the key store
        final KeyStore keyStore = KeyStoreUtils
                .getKeyStore(props.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE));
        try (final InputStream keyStoreStream = new FileInputStream(
                props.getProperty(NiFiProperties.SECURITY_KEYSTORE))) {
            keyStore.load(keyStoreStream,
                    props.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD).toCharArray());
        }
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());

        // if the key password is provided, try to use that - otherwise default to the keystore password
        if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_KEY_PASSWD))) {
            keyManagerFactory.init(keyStore,
                    props.getProperty(NiFiProperties.SECURITY_KEY_PASSWD).toCharArray());
        } else {
            keyManagerFactory.init(keyStore,
                    props.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD).toCharArray());
        }

        // initialize the ssl context
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        sslContext.getDefaultSSLParameters().setNeedClientAuth(props.getNeedClientAuth());

        return sslContext;

    } catch (final KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
            | UnrecoverableKeyException | KeyManagementException e) {
        throw new SslContextCreationException(e);
    }
}

From source file:be.fedict.eid.idp.sp.protocol.openid.OpenIDTrustManager.java

/**
 * Trust only the given server certificate, and the default trusted server
 * certificates./*from   w  w w  . j a v  a 2 s . c  om*/
 * 
 * @param serverCertificate
 *            SSL certificate to trust
 * @throws NoSuchAlgorithmException
 *             could not get an SSLContext instance
 * @throws KeyStoreException
 *             failed to intialize the {@link OpenIDTrustManager}
 */
public OpenIDTrustManager(X509Certificate serverCertificate)
        throws NoSuchAlgorithmException, KeyStoreException {
    this.serverCertificate = serverCertificate;
    String algorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(algorithm);
    trustManagerFactory.init((KeyStore) null);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    for (TrustManager trustManager : trustManagers) {
        if (trustManager instanceof X509TrustManager) {
            this.defaultTrustManager = (X509TrustManager) trustManager;
            break;
        }
    }
    if (null == this.defaultTrustManager) {
        throw new IllegalStateException("no default X509 trust manager found");
    }
}

From source file:gobblin.security.ssl.SSLContextFactory.java

/**
 * Create a {@link SSLContext} instance/*from w  w w . ja va  2 s  .c  om*/
 *
 * @param keyStoreFile a p12 or jks file depending on key store type
 * @param keyStorePassword password to access the key store
 * @param keyStoreType type of key store
 * @param trustStoreFile a jks file
 * @param trustStorePassword password to access the trust store
 */
public static SSLContext createInstance(File keyStoreFile, String keyStorePassword, String keyStoreType,
        File trustStoreFile, String trustStorePassword) {
    if (!keyStoreType.equalsIgnoreCase(P12_STORE_TYPE_NAME)
            && !keyStoreType.equalsIgnoreCase(JKS_STORE_TYPE_NAME)) {
        throw new IllegalArgumentException("Unsupported keyStoreType: " + keyStoreType);
    }

    try {
        // Load KeyStore
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(toInputStream(keyStoreFile), keyStorePassword.toCharArray());

        // Load TrustStore
        KeyStore trustStore = KeyStore.getInstance(JKS_STORE_TYPE_NAME);
        trustStore.load(toInputStream(trustStoreFile), trustStorePassword.toCharArray());

        // Set KeyManger from keyStore
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(DEFAULT_ALGORITHM);
        kmf.init(keyStore, keyStorePassword.toCharArray());

        // Set TrustManager from trustStore
        TrustManagerFactory trustFact = TrustManagerFactory.getInstance(DEFAULT_ALGORITHM);
        trustFact.init(trustStore);

        // Set Context to TLS and initialize it
        SSLContext sslContext = SSLContext.getInstance(DEFAULT_PROTOCOL);
        sslContext.init(kmf.getKeyManagers(), trustFact.getTrustManagers(), null);

        return sslContext;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.wso2.msf4j.conf.SSLHandlerFactory.java

public SSLHandlerFactory(SSLConfig sslConfig) {
    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
        algorithm = "SunX509";
    }/*from  w ww  . jav  a2s .c  om*/
    try {
        KeyStore ks = getKeyStore(sslConfig.getKeyStore(), sslConfig.getKeyStorePassword());
        // Set up key manager factory to use our key store
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
        kmf.init(ks,
                sslConfig.getCertificatePassword() != null ? sslConfig.getCertificatePassword().toCharArray()
                        : sslConfig.getKeyStorePassword().toCharArray());
        KeyManager[] keyManagers = kmf.getKeyManagers();
        TrustManager[] trustManagers = null;
        if (sslConfig.getTrustKeyStore() != null) {
            this.needClientAuth = true;
            KeyStore tks = getKeyStore(sslConfig.getTrustKeyStore(), sslConfig.getTrustKeyStorePassword());
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
            tmf.init(tks);
            trustManagers = tmf.getTrustManagers();
        }
        serverContext = SSLContext.getInstance(protocol);
        serverContext.init(keyManagers, trustManagers, null);
    } catch (UnrecoverableKeyException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException
            | IOException e) {
        throw new IllegalArgumentException("Failed to initialize the server-side SSLContext", e);
    }
}

From source file:com.lyndir.lhunath.opal.network.SSLFactory.java

private SSLFactory(final File keyStore, final String password) {

    try (InputStream keyStoreStream = new FileInputStream(keyStore)) {
        KeyStore store = KeyStore.getInstance("JKS");
        store.load(keyStoreStream, password.toCharArray());

        TrustManagerFactory tFactory = TrustManagerFactory.getInstance("SunX509");
        tFactory.init(store);//from  w  ww.  j  av  a2  s  .c  om

        context = SSLContext.getInstance("TLS");
        context.init(null, tFactory.getTrustManagers(), null);
    } catch (final KeyStoreException e) {
        throw new IllegalArgumentException(
                "Keystore type not supported or keystore could not be used to initialize trust.", e);
    } catch (final NoSuchAlgorithmException e) {
        throw new IllegalStateException("Key algorithm not supported.", e);
    } catch (final CertificateException e) {
        throw new IllegalArgumentException("Keystore could not be loaded.", e);
    } catch (final FileNotFoundException e) {
        throw new IllegalArgumentException("Keystore not found.", e);
    } catch (final IOException e) {
        throw new RuntimeException("Could not read the keys from the keystore.", e);
    } catch (final KeyManagementException e) {
        throw new RuntimeException("Could not use the keys for trust.", e);
    }
}

From source file:com.baasbox.android.HttpUrlConnectionClient.java

private static SSLSocketFactory createSocketFactory(Context context, int certStoreId, String certPassword) {
    TrustManagerFactory tmf;//from  w ww.  j a  v  a 2s.  c o  m
    InputStream in = null;
    try {
        in = context.getResources().openRawResource(certStoreId);
        KeyStore keyStore = KeyStore.getInstance("BKS");
        keyStore.load(in, certPassword.toCharArray());

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

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

        return sslContext.getSocketFactory();
    } catch (Exception e) {
        throw new BaasRuntimeException(e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // swallow
            }
        }
    }
}

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

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

    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:ch.truesolutions.payit.https.EasyX509TrustManager.java

/**
 * Constructor for EasyX509TrustManager.
 */// w  w w.j a  va 2  s  .c o m
public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
    super();
    keyStore = keystore;
    TrustManagerFactory factory = TrustManagerFactory.getInstance("SunX509");
    factory.init(keystore);
    TrustManager[] trustmanagers = factory.getTrustManagers();
    if (trustmanagers.length == 0) {
        throw new NoSuchAlgorithmException("SunX509 trust manager not supported");
    }
    this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}