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.cloudcoder.builder2.server.WebappSocketFactory.java

private SSLSocketFactory createSocketFactory() throws IOException, GeneralSecurityException {
    String keyStoreType = "JKS";
    String keystoreFilename = options.getKeystoreFilename();
    InputStream keyStoreInputStream = this.getClass().getClassLoader().getResourceAsStream(keystoreFilename);
    if (keyStoreInputStream == null) {
        throw new IOException("Could not load keystore " + keystoreFilename);
    }/*from  ww  w.jav  a2  s .co m*/

    KeyStore keyStore;
    String keystorePassword = options.getKeystorePassword();
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(keyStoreInputStream, keystorePassword.toCharArray());
    } finally {
        IOUtils.closeQuietly(keyStoreInputStream);
    }

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX", "SunJSSE");
    //trustManagerFactory.init(trustStore);
    // XXX Load the cert (public key) here instead of the private key?
    trustManagerFactory.init(keyStore);

    // TrustManager
    X509TrustManager x509TrustManager = null;
    for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
        if (trustManager instanceof X509TrustManager) {
            x509TrustManager = (X509TrustManager) trustManager;
            break;
        }
    }
    if (x509TrustManager == null) {
        throw new IllegalArgumentException("Cannot find x509TrustManager");
    }

    // KeyManager
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
    keyManagerFactory.init(keyStore, keystorePassword.toCharArray());
    X509KeyManager x509KeyManager = null;
    for (KeyManager keyManager : keyManagerFactory.getKeyManagers()) {
        if (keyManager instanceof X509KeyManager) {
            x509KeyManager = (X509KeyManager) keyManager;
            break;
        }
    }
    if (x509KeyManager == null) {
        throw new NullPointerException();
    }

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(new KeyManager[] { x509KeyManager }, new TrustManager[] { x509TrustManager }, null);

    return sslContext.getSocketFactory();
}

From source file:org.hyperic.util.security.DatabaseSSLProviderImpl.java

private TrustManagerFactory getTrustManagerFactory(final KeyStore keystore)
        throws KeyStoreException, IOException {
    try {//from w  w w  .j a  va2s.  c  o  m
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keystore);
        return trustManagerFactory;
    } catch (NoSuchAlgorithmException e) {
        // no support for algorithm, if this happens we're kind of screwed
        // we're using the default so it should never happen
        log.error("The algorithm is not supported. Error message:" + e.getMessage());
        throw new KeyStoreException(e);
    }
}

From source file:at.diamonddogs.net.SSLHelper.java

/**
 * Register a keystore with SSL (JAVA)/*  w  ww.  ja  v  a 2 s. c  om*/
 * 
 * @param c
 *            a {@link Context}
 * @param resourceId
 *            the resource id of the keystore
 * @param password
 *            the password of the keystore
 * @return true on success, false otherwise
 */
public boolean initSSLFactoryJava(Context c, int resourceId, String password) {
    try {
        if (c == null || resourceId == -1 || password == null) {
            LOGGER.info("No keystore specified, using alltrust");
            makeAllTrustManagerForJava();
            return true;
        } else {
            KeyStore store = getKeyStore(c, resourceId, password);
            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(store);
            SSLContext sslCtx = SSLContext.getInstance("TLS");
            sslCtx.init(null, tmf.getTrustManagers(), null);
            SSL_FACTORY_JAVA = sslCtx.getSocketFactory();
            sslState.trustAll = false;
            return true;
        }
    } catch (Throwable tr) {
        LOGGER.warn("Error initializing SSLFactoryJava", tr);
        try {
            makeAllTrustManagerForJava();
            sslState.tr = tr;
            return true;
        } catch (Throwable tr1) {
            sslState.tr1 = tr1;
            sslState.sslOk = false;
            LOGGER.warn("Error trusting all certs, no ssl connection possible", tr);
        }
        return false;
    }
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java

private IdmClient createIdmClient(AccessToken accessToken, String domainControllerFQDN,
        int domainControllerPort) throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(this.keyStore);
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    IdmClient idmClient = new IdmClient(domainControllerFQDN, domainControllerPort,
            new DefaultHostnameVerifier(), sslContext);
    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;
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java

private VmdirClient createVMdirClient(AccessToken accessToken, String domainControllerFQDN,
        int domainControllerPort) throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(this.keyStore);
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    VmdirClient vmdirClient = new VmdirClient(domainControllerFQDN, domainControllerPort,
            new DefaultHostnameVerifier(), sslContext);
    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);
    vmdirClient.setToken(restAccessToken);
    return vmdirClient;
}

From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java

public ConnectionHandler() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, KeyManagementException {

    InputStream keyStoreStream = getClass().getResourceAsStream("/web/module/resources/truststore.jks");

    // Load the keyStore
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(keyStoreStream, "Jembi#123".toCharArray());
    keyStoreStream.close();//from w  w  w.ja va  2  s.  co m

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);

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

    // set SSL Factory to be used for all HTTPS connections
    sslFactory = ctx.getSocketFactory();
    setImplementationId();
}

From source file:com.twinsoft.convertigo.engine.MySSLSocketFactory.java

private SSLContext createEasySSLContext()
        throws NoSuchProviderException, NoSuchAlgorithmException, KeyManagementException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, IOException {
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Creating SSL context");

    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Using KeyManager algorithm " + algorithm);

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);

    String keyStoreType = keyStore.endsWith(".pkcs11") ? "pkcs11" : "pkcs12";
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Key store type: " + keyStoreType);

    String alias = null;/*from ww w. j a v  a2  s. com*/
    KeyStore ks, ts;
    char[] passPhrase;

    if (keyStore.equals("") || (keyStore.endsWith(".udv"))) {
        ks = KeyStore.getInstance(keyStoreType);
        ks.load(null, keyStorePassword.toCharArray());
        kmf.init(ks, null);
    } else {
        File file = new File(keyStore);

        Properties properties = new Properties();
        properties.load(
                new FileInputStream(Engine.CERTIFICATES_PATH + CertificateManager.STORES_PROPERTIES_FILE_NAME));
        String p = properties.getProperty(file.getName(), "");
        int i = p.indexOf('/');
        if (i != -1) {
            alias = p.substring(i + 1);
        }

        if (keyStoreType.equals("pkcs11")) {
            String providerName = file.getName();
            providerName = "SunPKCS11-" + providerName.substring(0, providerName.lastIndexOf('.'));
            Engine.logCertificateManager.debug("(MySSLSocketFactory) Provider name: '" + providerName + "'");

            String pinCode;
            if (i == -1) {
                pinCode = Crypto2.decodeFromHexString(p);
            } else {
                pinCode = Crypto2.decodeFromHexString(p.substring(0, i));
            }

            Engine.logCertificateManager.debug("(MySSLSocketFactory) PIN code: " + pinCode);

            ks = KeyStore.getInstance("pkcs11", providerName);
            ks.load((InputStream) null, pinCode.toCharArray());
            kmf.init(ks, null);
        } else {
            ks = KeyStore.getInstance(keyStoreType);
            passPhrase = keyStorePassword.toCharArray();
            ks.load(new FileInputStream(keyStore), passPhrase);
            kmf.init(ks, passPhrase);
        }
    }
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Client alias: "
            + (alias == null ? "<to be chosen by the security implementor>" : alias));

    ts = KeyStore.getInstance("jks");
    passPhrase = trustStorePassword.toCharArray();
    if (trustStore.equals(""))
        ts.load(null, passPhrase);
    else
        ts.load(new FileInputStream(trustStore), passPhrase);

    algorithm = TrustManagerFactory.getDefaultAlgorithm();
    Engine.logCertificateManager.debug("(MySSLSocketFactory) Using TrustManager algorithm " + algorithm);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
    tmf.init(ts);

    TrustManager[] tm = { TRUST_MANAGER };

    MyX509KeyManager xkm = new MyX509KeyManager((X509KeyManager) kmf.getKeyManagers()[0], ks, ts, alias);

    Engine.logCertificateManager
            .debug("(MySSLSocketFactory) trusting all certificates : " + trustAllServerCertificates);

    //SSLContext context = SSLContext.getInstance("SSLv3");
    SSLContext context = SSLContext.getInstance("TLS");
    if (trustAllServerCertificates)
        context.init(new KeyManager[] { xkm }, tm, null);
    else
        context.init(new KeyManager[] { xkm }, tmf.getTrustManagers(), null);

    Engine.logCertificateManager.debug("(MySSLSocketFactory) SSL context created: " + context.getProtocol());
    return context;
}

From source file:com.amazon.alexa.avs.auth.companionservice.CompanionServiceClient.java

/**
 * Loads the CA certificate into an in-memory keystore and creates an {@link SSLSocketFactory}.
 *
 * @return SSLSocketFactory// w  ww  .java2  s . com
 */
public SSLSocketFactory getPinnedSSLSocketFactory() {
    InputStream caCertInputStream = null;
    InputStream clientKeyPair = null;
    try {
        // Load the CA certificate into memory
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        caCertInputStream = new FileInputStream(deviceConfig.getCompanionServiceInfo().getSslCaCert());
        Certificate caCert = cf.generateCertificate(caCertInputStream);

        // Load the CA certificate into the trusted KeyStore
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setCertificateEntry("myca", caCert);

        // Create a TrustManagerFactory with the trusted KeyStore
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        // Load the client certificate and private key into another KeyStore
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        clientKeyPair = new FileInputStream(deviceConfig.getCompanionServiceInfo().getSslClientKeyStore());
        keyStore.load(clientKeyPair,
                deviceConfig.getCompanionServiceInfo().getSslClientKeyStorePassphrase().toCharArray());

        // Create a TrustManagerFactory with the client key pair KeyStore
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore,
                deviceConfig.getCompanionServiceInfo().getSslClientKeyStorePassphrase().toCharArray());

        // Initialize the SSLContext and return an SSLSocketFactory;
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        return sc.getSocketFactory();
    } catch (CertificateException | KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException
            | IOException | KeyManagementException e) {
        throw new RuntimeException("The KeyStore for contacting the Companion Service could not be loaded.", e);
    } finally {
        IOUtils.closeQuietly(caCertInputStream);
        IOUtils.closeQuietly(clientKeyPair);
    }
}

From source file:org.disrupted.rumble.database.statistics.StatisticManager.java

public void onEventAsync(LinkLayerStarted event) {
    if (!event.linkLayerIdentifier.equals(WifiLinkLayerAdapter.LinkLayerIdentifier))
        return;/*from w ww  .  j  a v a  2s  .co m*/

    if (RumblePreferences.UserOkWithSharingAnonymousData(RumbleApplication.getContext())
            && RumblePreferences.isTimeToSync(RumbleApplication.getContext())) {
        if (!NetUtil.isURLReachable("http://disruptedsystems.org/"))
            return;

        try {
            // generate the JSON file
            byte[] json = generateStatJSON().toString().getBytes();

            // configure SSL
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            InputStream caInput = new BufferedInputStream(
                    RumbleApplication.getContext().getAssets().open("certs/disruptedsystemsCA.pem"));
            Certificate ca = cf.generateCertificate(caInput);

            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);

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

            URL url = new URL("https://data.disruptedsystems.org/post");
            HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());

            // then configure the header
            urlConnection.setInstanceFollowRedirects(true);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
            urlConnection.setRequestProperty("charset", "utf-8");
            urlConnection.setRequestProperty("Content-Length", Integer.toString(json.length));
            urlConnection.setUseCaches(false);

            // connect and send the JSON
            urlConnection.setConnectTimeout(10 * 1000);
            urlConnection.connect();
            urlConnection.getOutputStream().write(json);
            if (urlConnection.getResponseCode() != 200)
                throw new IOException("request failed");

            // erase the database
            RumblePreferences.updateLastSync(RumbleApplication.getContext());
            cleanDatabase();
        } catch (Exception ex) {
            Log.e(TAG, "Failed to establish SSL connection to server: " + ex.toString());
        }
    }
}

From source file:org.apache.ambari.server.controller.internal.URLStreamProvider.java

protected HttpsURLConnection getSSLConnection(String spec) throws IOException {

    if (sslSocketFactory == null) {
        synchronized (this) {
            if (sslSocketFactory == null) {
                try {
                    FileInputStream in = new FileInputStream(new File(path));
                    KeyStore store = KeyStore.getInstance(type == null ? KeyStore.getDefaultType() : type);

                    store.load(in, password.toCharArray());
                    in.close();/*from w  w w  . ja va  2  s.  com*/

                    TrustManagerFactory tmf = TrustManagerFactory
                            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

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

                    sslSocketFactory = context.getSocketFactory();
                } catch (Exception e) {
                    throw new IOException("Can't get connection.", e);
                }
            }
        }
    }
    HttpsURLConnection connection = (HttpsURLConnection) (new URL(spec).openConnection());

    connection.setSSLSocketFactory(sslSocketFactory);

    return connection;
}