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:org.hyperic.util.security.DefaultSSLProviderImpl.java

private TrustManagerFactory getTrustManagerFactory(final KeyStore keystore)
        throws KeyStoreException, IOException {
    try {//from   w w  w .  jav a2 s  .  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: " + e, e);
        throw new KeyStoreException(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()
 *//*from  w  w w .  j a  v  a  2  s  .co  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.vtc.basetube.services.volley.ssl.EasySSLSocketFactory.java

private static SSLContext createEasySSLContext(Context context) throws IOException {
    try {//from w  ww .j a  va2s.c om
        // Client should authenticate itself with the valid certificate to
        // Server.
        InputStream clientStream = context.getResources().openRawResource(CERTIFICATE_RESOURCE_CLIENT);
        char[] password = "XXXXXXXXXXXXX".toCharArray();

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(clientStream, password);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, password);

        // Client should also add the CA certificate obtained from server
        // and create TrustManager from it for the client to validate the
        // identity of the server.
        KeyStore trustStore = KeyStore.getInstance("BKS");
        InputStream instream = null;
        instream = context.getResources().openRawResource(CERTIFICATE_RESOURCE_CA);

        try {
            trustStore.load(instream, "XXXXXXXX".toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                instream.close();
            } catch (Exception ignore) {
            }
        }

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

        // Create an SSLContext that uses our TrustManager & Keystore
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);

        return sslContext;
    } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
    }
}

From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java

public static HttpClient getHttpsClient(Certificate[] sslCertificate) {
    DefaultHttpClient httpClient;//from w w w  .j av  a  2  s. c  om

    httpClient = new DefaultHttpClient();
    try {
        TrustManagerFactory tf = TrustManagerFactory.getInstance("X509");
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null);
        for (int i = 0; i < sslCertificate.length; i++) {
            ks.setCertificateEntry("StartCom" + i, sslCertificate[i]);
        }

        tf.init(ks);
        TrustManager[] tm = tf.getTrustManagers();

        SSLContext sslCon = SSLContext.getInstance("SSL");
        sslCon.init(null, tm, new SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(ks);
        Scheme sch = new Scheme("https", 443, socketFactory);

        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException | UnrecoverableKeyException ex) {
        Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
    }

    return httpClient;
}

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);//  w  w  w.  ja v a2 s  .c om
    final TrustManager[] trustManagers = factory.getTrustManagers();

    if (trustManagers.length == 0) {
        throw new NoSuchAlgorithmException("No trust manager found"); //$NON-NLS-1$
    }

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

    standardTrustManager = (X509TrustManager) trustManagers[0];
}

From source file:com.alliander.osgp.shared.usermanagement.UserManagementClient.java

/**
 * Construct a UserManagementClient instance.
 *
 * @param keystoreLocation//w  ww. j  a va  2 s .c  o  m
 *            The location of the key store.
 * @param keystorePassword
 *            The password for the key store.
 * @param keystoreType
 *            The type of the key store.
 * @param baseAddress
 *            The base address or URL for the UserManagementClient.
 *
 * @throws UserManagementClientException
 *             In case the construction fails, a
 *             UserManagmentClientException will be thrown.
 */
public UserManagementClient(final String keystoreLocation, final String keystorePassword,
        final String keystoreType, final String baseAddress) throws UserManagementClientException {

    InputStream stream = null;
    boolean isClosed = false;
    Exception exception = null;

    try {
        // Create the KeyStore.
        final KeyStore keystore = KeyStore.getInstance(keystoreType.toUpperCase());

        stream = new FileInputStream(keystoreLocation);
        keystore.load(stream, keystorePassword.toCharArray());

        // Create TrustManagerFactory and initialize it using the KeyStore.
        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystore);

        // Create Apache CXF WebClient with JSON provider.
        final List<Object> providers = new ArrayList<Object>();
        providers.add(new JacksonJaxbJsonProvider());

        this.webClient = WebClient.create(baseAddress, providers);
        if (this.webClient == null) {
            throw new UserManagementClientException("webclient is null");
        }

        // Set up the HTTP Conduit to use the TrustManagers.
        final ClientConfiguration config = WebClient.getConfig(this.webClient);
        final HTTPConduit conduit = config.getHttpConduit();

        conduit.setTlsClientParameters(new TLSClientParameters());
        conduit.getTlsClientParameters().setTrustManagers(tmf.getTrustManagers());
    } catch (final Exception e) {
        LOGGER.error(CONSTRUCTION_FAILED, e);
        throw new UserManagementClientException(CONSTRUCTION_FAILED, e);
    } finally {
        try {
            stream.close();
            isClosed = true;
        } catch (final Exception streamCloseException) {
            LOGGER.error(CONSTRUCTION_FAILED, streamCloseException);
            exception = streamCloseException;
        }
    }

    if (!isClosed) {
        throw new UserManagementClientException(CONSTRUCTION_FAILED, exception);
    }
}

From source file:com.amalto.workbench.utils.SSLContextProvider.java

private static TrustManager[] buildTrustManagers(String path, String storePass, String trusttype)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        UnrecoverableKeyException {
    InputStream stream = null;/*  w  w  w  .java  2 s .  co m*/
    try {
        if (StringUtils.isEmpty(path)) {
            return new TrustManager[] { TRUST_ALL };
        }
        if (!new File(path).exists()) {
            throw new KeyStoreException(Messages.bind(Messages.noKeystoreFile_error, path));
        }
        stream = new FileInputStream(path);

        KeyStore tks = KeyStore.getInstance(trusttype);
        tks.load(stream, storePass.toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); //$NON-NLS-1$
        tmf.init(tks);

        return tmf.getTrustManagers();
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:org.openo.nfvo.vnfmadapter.service.csm.connect.AbstractSslContext.java

protected static TrustManager[] createTrustManager(JSONObject sslConf) {
    TrustManager[] tms = null;/*from w  w w.jav a 2  s .c o m*/
    try {

        String TRUST_STORE = "etc/conf/trust.jks";
        String TRUST_STORE_PASSWORD = "Changeme_123";
        String TRUST_STORE_TYPE = "jks";
        if (sslConf != null) {
            TRUST_STORE = sslConf.getString("trustStore");
            TRUST_STORE_PASSWORD = sslConf.getString("trustStorePass");
            TRUST_STORE_TYPE = sslConf.getString("trustStoreType");
        }
        FileInputStream f_trustStore = new FileInputStream(TRUST_STORE);
        KeyStore ks = KeyStore.getInstance(TRUST_STORE_TYPE);
        ks.load(f_trustStore, TRUST_STORE_PASSWORD.toCharArray());
        f_trustStore.close();

        String alg = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmFact = TrustManagerFactory.getInstance(alg);
        tmFact.init(ks);
        tms = tmFact.getTrustManagers();

    } catch (Exception e) {
        LOG.error("create TrustManager fail!", e);
    }
    return tms;
}

From source file:com.alphabetbloc.accessmrs.utilities.MyTrustManager.java

public MyTrustManager(KeyStore localKeyStore) {

    try {/* w  w w .j  a v  a  2s  .co  m*/
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init((KeyStore) null);

        defaultTrustManager = findX509TrustManager(tmf);
        if (defaultTrustManager == null) {
            throw new IllegalStateException("Couldn't find X509TrustManager");
        }

        localTrustManager = new LocalStoreX509TrustManager(localKeyStore);

        List<X509Certificate> allIssuers = new ArrayList<X509Certificate>();

        for (X509Certificate cert : localTrustManager.getAcceptedIssuers()) {
            allIssuers.add(cert);
        }
        for (X509Certificate cert : defaultTrustManager.getAcceptedIssuers()) {
            allIssuers.add(cert);
        }
        acceptedIssuers = allIssuers.toArray(new X509Certificate[allIssuers.size()]);
    } catch (GeneralSecurityException e) {
        Log.e(TAG, "We have caught an exception in creating a trust manager!");
        throw new RuntimeException(e);
    }

}

From source file:com.oneis.common.utils.SSLCertificates.java

public static SSLContext load(String keysDirectory, String certsName, String clientCAName, boolean quiet)
        throws Exception {
    // For some indiciation of what's going on early in the boot process
    if (!quiet) {
        System.out.println("Loading " + certsName + " SSL certificates from " + keysDirectory);
    }/*from  w w  w. ja v a2 s.  c  o m*/

    // Get filenames
    String keyPathname = keysDirectory + "/" + certsName + ".key";
    String certPathname = keysDirectory + "/" + certsName + ".crt";
    final String intermediateCertPathnameBase = keysDirectory + "/" + certsName + "-intermediate";
    String clientCAPathname = null;
    if (clientCAName != null) {
        clientCAPathname = keysDirectory + "/" + clientCAName + ".crt";
    }

    if (!new File(keyPathname).exists()) {
        System.out.println("Doesn't exist: " + keyPathname);
        return null;
    }
    if (!new File(certPathname).exists()) {
        System.out.println("Doesn't exist: " + certPathname);
        return null;
    }
    if (clientCAPathname != null) {
        if (!new File(clientCAPathname).exists()) {
            System.out.println("Doesn't exist: " + clientCAPathname);
            return null;
        }
    }

    char[] nullPassword = {};

    PrivateKey privateKey = readPEMPrivateKey(keyPathname);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    // Server certificate
    ArrayList<java.security.cert.Certificate> certList = new ArrayList<java.security.cert.Certificate>(4);
    java.security.cert.Certificate cert = cf.generateCertificate(readPEM(certPathname));
    certList.add(cert);
    // Optional intermediate certificates
    int intermediateCounter = 1;
    while (true) {
        String intermediateCertPathname = intermediateCertPathnameBase;
        if (intermediateCounter != 1) {
            intermediateCertPathname += "-" + intermediateCounter;
        }
        intermediateCounter++;
        intermediateCertPathname += ".crt";
        if (new File(intermediateCertPathname).exists()) {
            certList.add(cf.generateCertificate(readPEM(intermediateCertPathname)));
        } else {
            // End of cert list
            break;
        }
    }
    // Optional client CA certificate
    java.security.cert.Certificate clientCACert = null;
    if (clientCAPathname != null) {
        clientCACert = cf.generateCertificate(readPEM(clientCAPathname));
    }
    if (clientCAName != null && clientCACert == null) {
        throw new RuntimeException("Logic error, failed to load client CA cert when required");
    }

    KeyStore ks = KeyStore.getInstance("JKS", "SUN");
    ks.load(null, nullPassword);
    ks.setKeyEntry("ONEIS", (Key) privateKey, "".toCharArray(),
            certList.toArray(new java.security.cert.Certificate[certList.size()]));

    if (clientCACert != null) {
        KeyStore.TrustedCertificateEntry tce = new KeyStore.TrustedCertificateEntry(clientCACert);
        ks.setEntry("CLIENTCA", tce, null);
    }

    // Generate some random Java API stuff, just for entertainment
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, nullPassword);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);

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

    if (!quiet) {
        System.out.println(" - server cert chain length " + certList.size()
                + (clientCACert != null ? ", requires client cert" : ", public server"));
    }
    return sslContext;
}