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.wcm.caravan.commons.httpclient.impl.helpers.CertificateLoader.java

/**
 * Build TrustManagerFactory.//from   www  . ja v a2  s.  c  o  m
 * @param trustStoreStream Truststore input stream
 * @param storeProperties store properties
 * @return TrustManagerFactory
 * @throws IOException
 * @throws GeneralSecurityException
 */
private static TrustManagerFactory getTrustManagerFactory(InputStream trustStoreStream,
        StoreProperties storeProperties) throws IOException, GeneralSecurityException {
    KeyStore jks = KeyStore.getInstance(storeProperties.getType());
    jks.load(trustStoreStream, storeProperties.getPassword().toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(storeProperties.getManagerType());
    tmf.init(jks);
    return tmf;
}

From source file:com.centeractive.ws.client.core.SoapClient.java

private void configureTls() {
    if (tlsEnabled == false) {
        return;/*from  w  w w. ja v  a2s.  c o m*/
    }
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
        context = SSLContext.getInstance(sslContextProtocol);
        context.init(null, new TrustManager[] { defaultTrustManager }, null);
        sslSocketFactory = context.getSocketFactory();
        ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
        if (strictHostVerification == false) {
            ((HttpsURLConnection) connection).setHostnameVerifier(new SoapHostnameVerifier());
        }
    } catch (GeneralSecurityException e) {
        throw new SoapClientException("TLS/SSL setup failed", e);
    }
}

From source file:com.evolveum.midpoint.prism.crypto.AESProtector.java

/**
 * @throws SystemException if jceks keystore is not available on {@link AESProtector#getKeyStorePath}
 *//*from   www.j  av a  2  s  .co m*/
public void init() {
    InputStream stream = null;
    try {
        // Test if use file or classpath resource
        File f = new File(getKeyStorePath());
        if (f.exists()) {
            LOGGER.info("Using file keystore at {}", getKeyStorePath());
            if (!f.canRead()) {
                LOGGER.error("Provided keystore file {} is unreadable.", getKeyStorePath());
                throw new EncryptionException(
                        "Provided keystore file " + getKeyStorePath() + " is unreadable.");
            }
            stream = new FileInputStream(f);

            // Use class path keystore
        } else {
            LOGGER.warn("Using default keystore from classpath ({}).", getKeyStorePath());
            // Read from class path

            stream = AESProtector.class.getClassLoader().getResourceAsStream(getKeyStorePath());
            // ugly dirty hack to have second chance to find keystore on
            // class path
            if (stream == null) {
                stream = AESProtector.class.getClassLoader()
                        .getResourceAsStream("com/../../" + getKeyStorePath());
            }
        }
        // Test if we have valid stream
        if (stream == null) {
            throw new EncryptionException("Couldn't load keystore as resource '" + getKeyStorePath() + "'");
        }
        // Load keystore
        keyStore.load(stream, getKeyStorePassword().toCharArray());
        stream.close();

        // Initialze trust manager list

        TrustManagerFactory tmFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmFactory.init(keyStore);
        trustManagers = new ArrayList<TrustManager>();
        for (TrustManager trustManager : tmFactory.getTrustManagers()) {
            trustManagers.add(trustManager);
        }

        //init apache crypto library
        Init.init();

    } catch (Exception ex) {
        LOGGER.error("Unable to work with keystore {}, reason {}.",
                new Object[] { getKeyStorePath(), ex.getMessage() }, ex);
        throw new SystemException(ex.getMessage(), ex);
    }
}

From source file:org.apache.axis2.transport.nhttp.HttpCoreNIOSSLListener.java

/**
 * Create the SSLContext to be used by this listener
 * @param transportIn the Axis2 transport description
 * @return the SSLContext to be used//from ww  w  . ja v  a  2s  . com
 */
protected SSLContext getSSLContext(TransportInDescription transportIn) throws AxisFault {

    KeyManager[] keymanagers = null;
    TrustManager[] trustManagers = null;

    Parameter keyParam = transportIn.getParameter("keystore");
    Parameter trustParam = transportIn.getParameter("truststore");

    if (keyParam != null) {
        OMElement ksEle = keyParam.getParameterElement().getFirstElement();
        String location = ksEle.getFirstChildWithName(new QName("Location")).getText();
        String type = ksEle.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = ksEle.getFirstChildWithName(new QName("Password")).getText();
        String keyPassword = ksEle.getFirstChildWithName(new QName("KeyPassword")).getText();

        try {
            KeyStore keyStore = KeyStore.getInstance(type);
            URL url = getClass().getClassLoader().getResource(location);
            log.debug("Loading Key Store from URL : " + url);

            keyStore.load(url.openStream(), storePassword.toCharArray());
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keyStore, keyPassword.toCharArray());
            keymanagers = kmfactory.getKeyManagers();

        } catch (GeneralSecurityException gse) {
            log.error("Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error("Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        }
    }

    if (trustParam != null) {
        OMElement tsEle = trustParam.getParameterElement().getFirstElement();
        String location = tsEle.getFirstChildWithName(new QName("Location")).getText();
        String type = tsEle.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = tsEle.getFirstChildWithName(new QName("Password")).getText();

        try {
            KeyStore trustStore = KeyStore.getInstance(type);
            URL url = getClass().getClassLoader().getResource(location);
            log.debug("Loading Trust Key Store from URL : " + url);

            trustStore.load(url.openStream(), storePassword.toCharArray());
            TrustManagerFactory trustManagerfactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerfactory.init(trustStore);
            trustManagers = trustManagerfactory.getTrustManagers();

        } catch (GeneralSecurityException gse) {
            log.error("Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error("Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        }
    }

    try {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, trustManagers, null);
        return sslcontext;

    } catch (GeneralSecurityException gse) {
        log.error("Unable to create SSL context with the given configuration", gse);
        throw new AxisFault("Unable to create SSL context with the given configuration", gse);
    }
}

From source file:edu.vt.middleware.ldap.LdapTLSSocketFactory.java

/**
 * This attempts to load the TrustManagers from the supplied <code>
 * InputStream</code> using the supplied password.
 *
 * @param  is  <code>InputStream</code> containing the truststore
 * @param  password  <code>String</code> to unlock the truststore
 * @param  storeType  <code>String</code> of truststore
 *
 * @return  <code>TrustManager[]</code>
 *
 * @throws  IOException  if the keystore cannot be loaded
 * @throws  GeneralSecurityException  if an errors occurs while loading the
 * TrustManagers//w w w . ja  v a 2 s  .  c  o m
 */
private TrustManager[] initTrustManager(final InputStream is, final String password, final String storeType)
        throws IOException, GeneralSecurityException {
    TrustManager[] tm = null;
    if (is != null) {
        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(this.loadKeyStore(is, password, storeType));
        tm = tmf.getTrustManagers();
    }
    return tm;
}

From source file:org.apache.ranger.services.nifi.client.NiFiConnectionMgr.java

private static SSLContext createSslContext(final String keystore, final char[] keystorePasswd,
        final String keystoreType, final String truststore, final char[] truststorePasswd,
        final String truststoreType, final String protocol) throws KeyStoreException, IOException,
        NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException {

    // prepare the keystore
    final KeyStore keyStore = KeyStore.getInstance(keystoreType);
    try (final InputStream keyStoreStream = new FileInputStream(keystore)) {
        keyStore.load(keyStoreStream, keystorePasswd);
    }//from   w w  w  .  j a  va  2 s. c  om
    final KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keystorePasswd);

    // prepare the truststore
    final KeyStore trustStore = KeyStore.getInstance(truststoreType);
    try (final InputStream trustStoreStream = new FileInputStream(truststore)) {
        trustStore.load(trustStoreStream, truststorePasswd);
    }
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    // initialize the ssl context
    final SSLContext sslContext = SSLContext.getInstance(protocol);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    return sslContext;
}

From source file:org.kontalk.client.ClientHTTPConnection.java

public static SSLSocketFactory setupSSLSocketFactory(Context context, PrivateKey privateKey,
        X509Certificate certificate, boolean acceptAnyCertificate)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        KeyManagementException, UnrecoverableKeyException, NoSuchProviderException {

    // in-memory keystore
    KeyManager[] km = null;/*  w  w  w  .ja va  2 s.  com*/
    if (privateKey != null && certificate != null) {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(null, null);
        keystore.setKeyEntry("private", privateKey, null, new Certificate[] { certificate });

        // key managers
        KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmFactory.init(keystore, null);
        km = kmFactory.getKeyManagers();
    }

    // trust managers
    TrustManager[] tm;

    if (acceptAnyCertificate) {
        tm = new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }
        } };
    } else {
        // load merged truststore (system + internal)
        KeyStore trustStore = InternalTrustStore.getTrustStore(context);

        // builtin keystore
        TrustManagerFactory tmFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmFactory.init(trustStore);

        tm = tmFactory.getTrustManagers();
    }

    SSLContext ctx = SSLContext.getInstance("TLSv1");
    ctx.init(km, tm, null);
    return new TlsOnlySocketFactory(ctx.getSocketFactory(), true);
}

From source file:org.apache.servicemix.http.processors.CommonsHttpSSLSocketFactory.java

protected final void createUnmanagedFactory(SslParameters ssl) throws Exception {
    SSLContext context;/*from ww w. java 2 s  .  c  o m*/
    if (ssl.getProvider() == null) {
        context = SSLContext.getInstance(ssl.getProtocol());
    } else {
        context = SSLContext.getInstance(ssl.getProtocol(), ssl.getProvider());
    }
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(ssl.getKeyManagerFactoryAlgorithm());
    String keyStore = ssl.getKeyStore();
    if (keyStore == null) {
        keyStore = System.getProperty("javax.net.ssl.keyStore");
        if (keyStore == null) {
            throw new IllegalArgumentException(
                    "keyStore or system property javax.net.ssl.keyStore must be set");
        }
    }
    if (keyStore.startsWith("classpath:")) {
        try {
            String res = keyStore.substring(10);
            URL url = new ClassPathResource(res).getURL();
            keyStore = url.toString();
        } catch (IOException e) {
            throw new JBIException("Unable to find keyStore " + keyStore, e);
        }
    }
    String keyStorePassword = ssl.getKeyStorePassword();
    if (keyStorePassword == null) {
        keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");
        if (keyStorePassword == null) {
            throw new IllegalArgumentException(
                    "keyStorePassword or system property javax.net.ssl.keyStorePassword must be set");
        }
    }
    String trustStore = ssl.getTrustStore();
    String trustStorePassword = null;
    if (trustStore == null) {
        trustStore = System.getProperty("javax.net.ssl.trustStore");
    }
    if (trustStore != null) {
        if (trustStore.startsWith("classpath:")) {
            try {
                String res = trustStore.substring(10);
                URL url = new ClassPathResource(res).getURL();
                trustStore = url.toString();
            } catch (IOException e) {
                throw new JBIException("Unable to find trustStore " + trustStore, e);
            }
        }
        trustStorePassword = ssl.getTrustStorePassword();
        if (trustStorePassword == null) {
            trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
            if (trustStorePassword == null) {
                throw new IllegalArgumentException(
                        "trustStorePassword or system property javax.net.ssl.trustStorePassword must be set");
            }
        }
    }
    KeyStore ks = KeyStore.getInstance(ssl.getKeyStoreType());
    ks.load(Resource.newResource(keyStore).getInputStream(), keyStorePassword.toCharArray());
    keyManagerFactory.init(ks,
            ssl.getKeyPassword() != null ? ssl.getKeyPassword().toCharArray() : keyStorePassword.toCharArray());
    if (trustStore != null) {
        KeyStore ts = KeyStore.getInstance(ssl.getTrustStoreType());
        ts.load(Resource.newResource(trustStore).getInputStream(), trustStorePassword.toCharArray());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(ssl.getTrustManagerFactoryAlgorithm());
        trustManagerFactory.init(ts);
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new java.security.SecureRandom());
    } else {
        context.init(keyManagerFactory.getKeyManagers(), null, new java.security.SecureRandom());
    }
    factory = context.getSocketFactory();
}

From source file:com.aware.ui.Plugins_Manager.java

/**
* Downloads and compresses image for optimized icon caching
* @param image_url/*from  ww w  .j  a v a2 s  .c  o  m*/
* @return
*/
public static byte[] cacheImage(String image_url, Context sContext) {
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = sContext.getResources().openRawResource(R.raw.aware);
        Certificate ca;
        try {
            ca = cf.generateCertificate(caInput);
        } finally {
            caInput.close();
        }

        KeyStore sKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream inStream = sContext.getResources().openRawResource(R.raw.awareframework);
        sKeyStore.load(inStream, "awareframework".toCharArray());
        inStream.close();

        sKeyStore.setCertificateEntry("ca", ca);

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

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

        //Fetch image now that we recognise SSL
        URL image_path = new URL(image_url.replace("http://", "https://")); //make sure we are fetching the images over https
        HttpsURLConnection image_connection = (HttpsURLConnection) image_path.openConnection();
        image_connection.setSSLSocketFactory(context.getSocketFactory());

        InputStream in_stream = image_connection.getInputStream();
        Bitmap tmpBitmap = BitmapFactory.decodeStream(in_stream);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        tmpBitmap.compress(Bitmap.CompressFormat.PNG, 100, output);

        return output.toByteArray();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.budrotech.jukebox.service.ssl.SSLSocketFactory.java

private static SSLContext createSSLContext(String algorithm, final KeyStore keystore,
        final String keyStorePassword, final SecureRandom random, final TrustStrategy trustStrategy)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, KeyManagementException {
    if (algorithm == null) {
        algorithm = TLS;//  ww w. j  a v a 2 s.  c  o  m
    }

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keystore, keyStorePassword != null ? keyStorePassword.toCharArray() : null);
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keystore);

    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    if (trustManagers != null && trustStrategy != null) {
        for (int i = 0; i < trustManagers.length; i++) {
            TrustManager tm = trustManagers[i];

            if (tm instanceof X509TrustManager) {
                trustManagers[i] = new TrustManagerDecorator((X509TrustManager) tm, trustStrategy);
            }
        }
    }

    SSLContext sslcontext = SSLContext.getInstance(algorithm);
    sslcontext.init(keyManagers, trustManagers, random);

    return sslcontext;
}