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.apache.hadoop.io.crypto.bee.RestClient.java

private InputStream httpsWithCertificate(final URL url) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null);// Make an empty store

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    FileInputStream fis = new FileInputStream(BeeConstants.BEE_HTTPS_CERTIFICATE_DEFAULT_PATH);
    BufferedInputStream bis = new BufferedInputStream(fis);
    while (bis.available() > 0) {
        Certificate cert = cf.generateCertificate(bis);
        // System.out.println(cert.getPublicKey().toString());
        trustStore.setCertificateEntry("jetty" + bis.available(), cert);
    }//from w  ww  .  ja va 2 s  .co  m

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, tmf.getTrustManagers(), null);
    SSLSocketFactory sslFactory = ctx.getSocketFactory();

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            if (0 == hostname.compareToIgnoreCase(url.getHost())) {
                return true;
            }
            return false;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(sslFactory);

    return urlConnection.getInputStream();
}

From source file:org.appenders.log4j2.elasticsearch.jest.JKSCertInfo.java

@Override
public void applyTo(HttpClientConfig.Builder clientConfigBuilder) {

    try (FileInputStream keystoreFile = new FileInputStream(new File(keystorePath));
            FileInputStream truststoreFile = new FileInputStream(new File(truststorePath))) {
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(keystoreFile, keystorePassword.toCharArray());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keystorePassword.toCharArray());

        KeyStore trustStore = KeyStore.getInstance("jks");
        trustStore.load(truststoreFile, truststorePassword.toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        // TODO: add support for hostname verification modes
        clientConfigBuilder.sslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        clientConfigBuilder//ww  w .ja  v  a2  s  . c  om
                .httpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

    } catch (IOException | GeneralSecurityException e) {
        throw new ConfigurationException(configExceptionMessage, e);
    }
}

From source file:br.com.ararati.operacoes.SocketFactory.java

public TrustManager[] createTrustManagers()
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    KeyStore trustStore = KeyStore.getInstance("JKS");

    trustStore.load(new FileInputStream(fileCacerts), "changeit".toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    return trustManagerFactory.getTrustManagers();
}

From source file:com.amazon.alexa.avs.companion.ProvisioningClient.java

private SSLSocketFactory getPinnedSSLSocketFactory(Context context) throws Exception {
    InputStream caCertInputStream = null;
    try {// w  w w .j  a  v  a2 s  . c o  m
        caCertInputStream = context.getResources().openRawResource(R.raw.ca);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate caCert = cf.generateCertificate(caCertInputStream);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setCertificateEntry("myca", caCert);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
        return sslContext.getSocketFactory();
    } finally {
        IOUtils.closeQuietly(caCertInputStream);
    }
}

From source file:org.ovirt.engine.core.uutils.net.HttpClientBuilder.java

public CloseableHttpClient build() throws IOException, GeneralSecurityException {
    // Prepare the default configuration for all requests:
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(connectTimeout != null ? connectTimeout : 0)
            .setSocketTimeout(readTimeout != null ? readTimeout : 0).build();

    // Configure the trust manager:
    TrustManager[] trustManager = null;
    if (verifyChain) {
        if (trustStore != null) {
            try (InputStream is = new FileInputStream(trustStore)) {
                KeyStore ks = KeyStore.getInstance(trustStoreType);
                ks.load(is, StringUtils.isEmpty(trustStorePassword) ? null : trustStorePassword.toCharArray());
                TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm);
                tmf.init(ks);
                trustManager = tmf.getTrustManagers();
            }/*from w ww.  j  av  a 2  s  . c  o  m*/
        }
    } else {
        trustManager = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[] {};
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
    }

    // Create the SSL context:
    SSLContext sslContext = SSLContext.getInstance(tlsProtocol);
    sslContext.init(null, trustManager, null);

    // Create the SSL host name verifier:
    HostnameVerifier sslHostnameVerifier = null;
    if (!verifyHost) {
        sslHostnameVerifier = (hostname, session) -> true;
    }

    // Create the socket factory for HTTP:
    ConnectionSocketFactory httpSocketFactory = new PlainConnectionSocketFactory();

    // Create the socket factory for HTTPS:
    ConnectionSocketFactory httpsSocketFactory = new SSLConnectionSocketFactory(sslContext,
            sslHostnameVerifier);

    // Create the socket factory registry:
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", httpSocketFactory).register("https", httpsSocketFactory).build();

    // Create the connection manager:
    HttpClientConnectionManager connectionManager;
    if (poolSize != null) {
        PoolingHttpClientConnectionManager poolManager = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);
        poolManager.setDefaultMaxPerRoute(poolSize);
        poolManager.setMaxTotal(poolSize);
        connectionManager = poolManager;
    } else {
        connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
    }

    // Create the client:
    return org.apache.http.impl.client.HttpClientBuilder.create().setDefaultRequestConfig(requestConfig)
            .setSSLHostnameVerifier(sslHostnameVerifier).setConnectionManager(connectionManager).build();
}

From source file:com.lhtechnologies.DoorApp.AuthenticatorService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent.getAction().equals(stopAction)) {
        stopSelf();/*w  w w . j av  a2 s  .  c o  m*/
    } else if (intent.getAction().equals(authenticateAction)) {
        //Check if we want to open the front door or flat door
        String doorToOpen = FrontDoor;
        String authCode = null;
        if (intent.hasExtra(FlatDoor)) {
            doorToOpen = FlatDoor;
            authCode = intent.getCharSequenceExtra(FlatDoor).toString();
        }

        if (intent.hasExtra(LetIn)) {
            doorToOpen = LetIn;
        }

        //Now run the connection code (Hope it runs asynchronously and we do not need AsyncTask --- NOPE --YES
        urlConnection = null;
        URL url;

        //Prepare the return intent
        Intent broadcastIntent = new Intent(AuthenticationFinishedBroadCast);

        try {
            //Try to create the URL, return an error if it fails
            url = new URL(address);

            if (!url.getProtocol().equals("https")) {
                throw new MalformedURLException("Please only use https protocol!");
            }

            String password = "password";
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(getResources().getAssets().open("LH Technologies Root CA.bks"),
                    password.toCharArray());

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

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

            urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setSSLSocketFactory(context.getSocketFactory());
            urlConnection.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("POST");

            urlConnection.setDoOutput(true);
            urlConnection.setChunkedStreamingMode(0);

            OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());

            //Write our stuff to the output stream;
            out.write("deviceName=" + deviceName + "&udid=" + udid + "&secret=" + secret + "&clientVersion="
                    + clientVersion + "&doorToOpen=" + doorToOpen);
            if (doorToOpen.equals(FlatDoor)) {
                out.write("&authCode=" + authCode);
                //Put an extra in so the return knows we opened the flat door
                broadcastIntent.putExtra(FlatDoor, FlatDoor);
            }

            out.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            //Read the answer
            String decodedString;
            String returnString = "";
            while ((decodedString = in.readLine()) != null) {
                returnString += decodedString;
            }
            in.close();

            broadcastIntent.putExtra(AuthenticatorReturnCode, returnString);

        } catch (MalformedURLException e) {
            broadcastIntent.putExtra(AuthenticatorReturnCode, ClientErrorMalformedURL);
        } catch (Exception e) {
            broadcastIntent.putExtra(AuthenticatorReturnCode, ClientErrorUndefined);
            broadcastIntent.putExtra(AuthenticatorErrorDescription, e.getLocalizedMessage());
        } finally {
            if (urlConnection != null)
                urlConnection.disconnect();
            //Now send a broadcast with the result
            sendOrderedBroadcast(broadcastIntent, null);
            Log.e(this.getClass().getSimpleName(), "Send Broadcast!");
        }
    }

}

From source file:org.appenders.log4j2.elasticsearch.jest.PEMCertInfo.java

@Override
public void applyTo(HttpClientConfig.Builder builder) {

    if (java.security.Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
        java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }/*w  w w  . ja v  a 2  s .  c  o  m*/

    try (FileInputStream clientCert = new FileInputStream(new File(clientCertPath));
            FileInputStream key = new FileInputStream(new File(keyPath));
            FileInputStream certificateAuthoritiies = new FileInputStream(new File(caPath))) {
        KeyStore keyStore = PemReader.loadKeyStore(clientCert, key, Optional.ofNullable(keyPassphrase));
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keyPassphrase.toCharArray());

        KeyStore trustStore = PemReader.loadTrustStore(certificateAuthoritiies);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        // TODO: add support for hostname verification modes
        builder.sslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        builder.httpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

    } catch (IOException | GeneralSecurityException e) {
        throw new ConfigurationException(configExceptionMessage, e);
    }

}

From source file:com.gamesalutes.utils.EncryptUtils.java

/**
 * Creates an <code>SSLContext</code> that uses the specified trusted certificates.
 * /*from w w w  . j  a  v a 2s.co m*/
 * @param protocol the {@link TransportSecurityProtocol} to use for the context
 * @param trustedCerts certificates to import into the <code>SSLContext</code> or <code>null</code>
 *         to accept all issuers
 * @param privateKey the client key to authenticate the client with the server
 * @return the created <code>SSLContext</code>
 * @throws Exception if error occurs during the process of creating the context
 */
public static SSLContext createSSLContext(TransportSecurityProtocol protocol, PrivateKey privateKey,
        java.security.cert.X509Certificate... trustedCerts) throws Exception {
    if (trustedCerts != null && trustedCerts.length == 0)
        throw new IllegalArgumentException("trustedCerts is empty");

    X509TrustManager defaultManager = null;
    KeyManager[] keyManagers = null;
    KeyStore keyStore = null;

    if (privateKey != null || trustedCerts != null) {
        // create a new key store instance that will install the certificates
        // and/or the private keys
        keyStore = KeyStore.getInstance(JKS_TYPE);
        keyStore.load(null, null);
    }

    // import the certs
    if (trustedCerts != null) {
        // set up the key manager for the certificates
        javax.net.ssl.TrustManagerFactory trustFact = javax.net.ssl.TrustManagerFactory
                .getInstance(KEY_MANAGEMENT_ALG_SUN_X509);

        // install the certificates in the key store and give them a unique alias
        int imported = 0;
        for (java.security.cert.X509Certificate cert : trustedCerts) {
            if (cert != null)
                keyStore.setCertificateEntry("cert" + ++imported, cert);
        }
        if (imported == 0)
            throw new IllegalArgumentException("no non-null certs in trustedCerts");
        // add the certs to the trust factory
        trustFact.init(keyStore);

        // get a default trust manager
        TrustManager[] tms = trustFact.getTrustManagers();
        if (tms != null && tms.length >= 1)
            defaultManager = (X509TrustManager) tms[0];
    }

    // import the private key
    if (privateKey != null) {
        keyStore.setKeyEntry("client", privateKey, null, null);
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(privateKey.getAlgorithm());

        kmfactory.init(keyStore, null);
        keyManagers = kmfactory.getKeyManagers();
    }
    //create the SSL context based on these parameters
    SSLContext sslContext = SSLContext.getInstance(protocol.toString());

    // use a CertX509TrustManager since default one will still fail validation for 
    // self-signed certs
    sslContext.init(keyManagers,
            new TrustManager[] { trustedCerts != null ? new CertX509TrustManager(defaultManager, trustedCerts)
                    : new CertX509TrustManager() },
            null);

    return sslContext;

}

From source file:org.mitre.svmp.net.SSLConfig.java

@SuppressLint("TrulyRandom")
private void doConfigure() throws KeyStoreException, CertificateException, NoSuchAlgorithmException,
        IOException, KeyManagementException {
    // find out if we should use the MemorizingTrustManager instead of the system trust store (set in Preferences)
    boolean useMTM = Utility.getPrefBool(context, R.string.preferenceKey_connection_useMTM,
            R.string.preferenceValue_connection_useMTM);

    // determine whether we should use client certificate authentication
    boolean useCertificateAuth = Constants.API_14 && (connectionInfo.getAuthType()
            & CertificateModule.AUTH_MODULE_ID) == CertificateModule.AUTH_MODULE_ID;

    // set up key managers
    KeyManager[] keyManagers = null;
    // if certificate authentication is enabled, use a key manager with the provided alias
    if (useCertificateAuth) {
        keyManagers = new KeyManager[] { new SVMPKeyManager(context, connectionInfo.getCertificateAlias()) };
    }/*from w ww.j a v  a  2  s. c om*/

    // set up trust managers
    TrustManager[] trustManagers = null;

    KeyStore localTrustStore = KeyStore.getInstance("BKS");
    InputStream in = context.getResources().openRawResource(R.raw.client_truststore);
    localTrustStore.load(in, Constants.TRUSTSTORE_PASSWORD.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(localTrustStore);

    // 1) If "res/raw/client_truststore.bks" is not empty, use it as the pinned cert trust store (default is empty)
    // 2) Otherwise, if the "Show certificate dialog" developer preference is enabled, use that (default is disabled)
    // 3) Otherwise, use the default system trust store, consists of normal trusted Android CA certs
    if (localTrustStore.size() > 0) {
        // this means that "res/raw/client_truststore.bks" has been replaced with a trust store that is not empty
        // we will use that "pinned" store to check server certificate trust
        Log.d(TAG, "SSLConfig: Using static BKS trust store to check server cert trust");
        trustManagers = trustManagerFactory.getTrustManagers();
        // After switching to WebSockets, MTM causes the app to freeze; removed for now
    } else if (useMTM) {
        // by default useMTM is false ("Show certificate dialog" in developer preferences)
        // this creates a certificate dialog to decide what to do with untrusted certificates, instead of flat-out rejecting them
        Log.d(TAG,
                "SSLConfig: Static BKS trust store is empty but MTM is enabled, using MTM to check server cert trust");
        mtm = new MemorizingTrustManager(context);
        mtm.bindDisplayActivity(activity);
        trustManagers = new X509TrustManager[] { mtm };
    } else {
        Log.d(TAG,
                "SSLConfig: Static BKS trust store is empty and MTM is disabled, using system trust store to check server cert trust");
        // leaving trustManagers null accomplishes this
    }

    PRNGFixes.apply(); // fix Android SecureRandom issue on pre-KitKat platforms
    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, new SecureRandom());
}

From source file:se.kth.infosys.lumberjack.protocol.LumberjackClient.java

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

    try {//from w  w  w.  j av a  2s  . c  om
        if (keyStoreFile == null) {
            throw new IOException("Key store not configured");
        }
        if (server == null) {
            throw new IOException("Server address not configured");
        }

        keyStore = KeyStore.getInstance("JKS");
        InputStream keystoreStream = this.getClass().getClassLoader().getResourceAsStream(keyStoreFile);
        keyStore.load(keystoreStream, null);
        keystoreStream.close();

        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);
        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);
    }
}