Example usage for javax.net.ssl TrustManagerFactory getTrustManagers

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

Introduction

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

Prototype

public final TrustManager[] getTrustManagers() 

Source Link

Document

Returns one trust manager for each type of trust material.

Usage

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()
 */// ww  w  .  java  2s  . co 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:org.apache.directory.studio.connection.core.io.StudioTrustManager.java

private X509TrustManager getTrustManager(KeyStore trustStore) throws CertificateException {
    try {//from   w w  w . jav  a  2s  .c o  m
        Enumeration<String> aliases = trustStore.aliases();
        if (aliases.hasMoreElements()) {
            TrustManagerFactory factory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            factory.init(trustStore);
            TrustManager[] permanentTrustManagers = factory.getTrustManagers();
            TrustManager permanentTrustManager = permanentTrustManagers[0];
            return (X509TrustManager) permanentTrustManager;
        }
    } catch (Exception e) {
        throw new CertificateException(Messages.StudioTrustManager_CantCreateTrustManager, e);
    }

    return null;
}

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

public DatabaseSSLProviderImpl(KeystoreConfig keystoreConfig, boolean acceptUnverifiedCertificates) {
    if (log.isDebugEnabled()) {
        log.debug("Keystore info: alias=" + keystoreConfig.getAlias() + ", path:" + keystoreConfig.getFilePath()
                + ", acceptUnverifiedCertificates=" + acceptUnverifiedCertificates);
    }/*from  w  ww  .ja  va 2  s .com*/
    boolean hasLock = false;
    final boolean debug = log.isDebugEnabled();
    final StopWatch watch = new StopWatch();
    try {
        KeystoreManager keystoreMgr = KeystoreManager.getKeystoreManager();
        KEYSTORE_READER_LOCK.lockInterruptibly();
        hasLock = true;
        KeyStore trustStore = keystoreMgr.getKeyStore(keystoreConfig);
        KeyManagerFactory keyManagerFactory = getKeyManagerFactory(trustStore,
                keystoreConfig.getFilePassword());
        TrustManagerFactory trustManagerFactory = getTrustManagerFactory(trustStore);
        X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
        X509TrustManager customTrustManager = getCustomTrustManager(defaultTrustManager, keystoreConfig,
                acceptUnverifiedCertificates, trustStore);
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { customTrustManager },
                new SecureRandom());
        // XXX Should we use ALLOW_ALL_HOSTNAME_VERIFIER (least restrictive) or 
        //     BROWSER_COMPATIBLE_HOSTNAME_VERIFIER (moderate restrictive) or
        //     STRICT_HOSTNAME_VERIFIER (most restrictive)???
        sslSocketFactory = new SSLSocketFactory(sslContext, getHostnameVerifier());
    } catch (Exception e) {
        throw new IllegalStateException(e);
    } finally {
        if (hasLock)
            KEYSTORE_READER_LOCK.unlock();
        if (debug)
            log.debug("readCert: " + watch);
    }
}

From source file:org.codice.ddf.spatial.ogc.catalog.common.TestTrustedRemoteSource.java

private TLSClientParameters getTLSParameters(KeyStore keyStore, String keystorePassword, KeyStore trustStore) {
    TLSClientParameters tlsParams = new TLSClientParameters();
    try {//from www .java 2  s  .c  om
        TrustManagerFactory trustFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustFactory.init(trustStore);
        TrustManager[] tm = trustFactory.getTrustManagers();
        tlsParams.setTrustManagers(tm);

        KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyFactory.init(keyStore, keystorePassword.toCharArray());
        KeyManager[] km = keyFactory.getKeyManagers();
        tlsParams.setKeyManagers(km);
    } catch (Exception e) {
        LOGGER.warn("Could not load keystores, may be an error with the filesystem", e);
    }

    FiltersType filter = new FiltersType();
    filter.getInclude().addAll(SecuritySettingsService.SSL_ALLOWED_ALGORITHMS);
    filter.getExclude().addAll(SecuritySettingsService.SSL_DISALLOWED_ALGORITHMS);
    tlsParams.setCipherSuitesFilter(filter);

    return tlsParams;
}

From source file:org.openanzo.client.AnzoTrustManager.java

public AnzoTrustManager(boolean trustAll, boolean showTrace) throws AnzoException {
    this.trustAll = trustAll;
    this.showTrace = showTrace;

    String truststorePath = CommandContext.preprocessString(System.getProperty("javax.net.ssl.trustStore"));
    String userHome = System.getProperty("user.home");
    try {//from  www. j  a  va  2s . c om
        if (truststorePath == null && userHome != null) {
            File truststoreFile = new File(new File(userHome, ANZO_DIR), DEFAULT_CLIENT_TRUST);
            if (truststoreFile.exists()) // check the default location for the trust store in the user's .anzo directory
                truststorePath = truststoreFile.getCanonicalPath();
        }
        String truststoreType = System.getProperty("javax.net.ssl.trustStoreType", "JCEKS");
        String truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_PWORD);

        // create a "default" JSSE X509TrustManager.
        KeyStore ks = KeyStore.getInstance(truststoreType);
        if (truststorePath != null && truststorePassword != null) {
            File trustFile = new File(truststorePath);
            if (trustFile.exists()) {
                ks.load(new FileInputStream(trustFile), truststorePassword.toCharArray());
            }
        }
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
        tmf.init(ks);
        TrustManager tms[] = tmf.getTrustManagers();

        /*
         * Iterate over the returned trustmanagers, look
         * for an instance of X509TrustManager.  If found,
         * use that as our "default" trust manager.
         */
        for (int i = 0; i < tms.length; i++) {
            if (tms[i] instanceof X509TrustManager) {
                x509tm = (X509TrustManager) tms[i];
                return;
            }
        }
    } catch (Exception e) {
        throw new AnzoException(ExceptionConstants.CLIENT.FAILED_INITIALIZE_TRUST_MANAGER, e);
    }

    // could not find the java default trust manager so throw an exception
    throw new AnzoRuntimeException(ExceptionConstants.CLIENT.FAILED_INITIALIZE_TRUST_MANAGER,
            "The default Java Trust Manager was not found");
}

From source file:org.apache.hadoop.security.ssl.ReloadingX509TrustManager.java

X509TrustManager loadTrustManager() throws IOException, GeneralSecurityException {
    X509TrustManager trustManager = null;
    KeyStore ks = KeyStore.getInstance(type);
    String tstorePassword;//from  w w w  .j  ava  2  s  . co m
    if (passwordFileLocation != null) {
        tstorePassword = FileUtils.readFileToString(passwordFileLocation);
    } else {
        tstorePassword = password;
    }
    FileInputStream in = new FileInputStream(file);
    try {
        ks.load(in, tstorePassword.toCharArray());
        lastLoaded = file.lastModified();
        LOG.debug("Loaded truststore '" + file + "'");
    } finally {
        in.close();
    }

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(SSLFactory.SSLCERTIFICATE);
    trustManagerFactory.init(ks);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    for (TrustManager trustManager1 : trustManagers) {
        if (trustManager1 instanceof X509TrustManager) {
            trustManager = (X509TrustManager) trustManager1;
            break;
        }
    }
    return trustManager;
}

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  a2s. c  om*/
    } 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.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  va  2  s  .  c  o  m
 */
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: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   www  . jav a2 s  .c o  m*/
        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);
    }
}

From source file:info.fetter.logstashforwarder.protocol.LumberjackClient.java

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

    try {/*from   w  ww .j  ava2s .c om*/
        if (keyStorePath == null) {
            throw new IOException("Key store not configured");
        }
        if (server == null) {
            throw new IOException("Server address not configured");
        }

        keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(keyStorePath), null);

        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);
        socket.setSoTimeout(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);
    }
}