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.apache.nifi.minifi.c2.integration.test.AbstractTestSecure.java

public static SSLContext initCertificates(Path certificatesDirectory, List<String> serverHostnames)
        throws Exception {
    List<String> toolkitCommandLine = new ArrayList<>(Arrays.asList("-O", "-o",
            certificatesDirectory.toFile().getAbsolutePath(), "-C", "CN=user1", "-C", "CN=user2", "-C",
            "CN=user3", "-C", "CN=user4", "-S", "badKeystorePass", "-K", "badKeyPass", "-P", "badTrustPass"));
    for (String serverHostname : serverHostnames) {
        toolkitCommandLine.add("-n");
        toolkitCommandLine.add(serverHostname);
    }//from  w w w  .j av a 2 s .  co m
    Files.createDirectories(certificatesDirectory);
    TlsToolkitStandaloneCommandLine tlsToolkitStandaloneCommandLine = new TlsToolkitStandaloneCommandLine();
    tlsToolkitStandaloneCommandLine.parse(toolkitCommandLine.toArray(new String[toolkitCommandLine.size()]));
    new TlsToolkitStandalone()
            .createNifiKeystoresAndTrustStores(tlsToolkitStandaloneCommandLine.createConfig());

    tlsToolkitStandaloneCommandLine = new TlsToolkitStandaloneCommandLine();
    tlsToolkitStandaloneCommandLine.parse(new String[] { "-O", "-o",
            certificatesDirectory.getParent().resolve("badCert").toFile().getAbsolutePath(), "-C",
            "CN=user3" });
    new TlsToolkitStandalone()
            .createNifiKeystoresAndTrustStores(tlsToolkitStandaloneCommandLine.createConfig());

    final KeyStore trustStore = KeyStoreUtils.getTrustStore("jks");
    try (final InputStream trustStoreStream = new FileInputStream(
            certificatesDirectory.resolve("c2").resolve("truststore.jks").toFile().getAbsolutePath())) {
        trustStore.load(trustStoreStream, "badTrustPass".toCharArray());
    }
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    return SslContextFactory.createTrustSslContext(
            certificatesDirectory.resolve("c2").resolve("truststore.jks").toFile().getAbsolutePath(),
            "badTrustPass".toCharArray(), "jks", "TLS");
}

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

/**
 * Construct an AuthenticationClient instance.
 *
 * @param keystoreLocation/* w  w w  .j  a  va  2  s.co 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 AuthenticationClient.
 *
 * @throws AuthenticationClientException
 *             In case the construction fails, an
 *             AuthenticationClientException will be thrown.
 */
public AuthenticationClient(final String keystoreLocation, final String keystorePassword,
        final String keystoreType, final String baseAddress) throws AuthenticationClientException {

    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, true);
        if (this.webClient == null) {
            throw new AuthenticationClientException("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());

        this.jacksonObjectMapper = new ObjectMapper();
    } catch (final Exception e) {
        LOGGER.error(CONSTRUCTION_FAILED, e);
        throw new AuthenticationClientException(CONSTRUCTION_FAILED, e);
    } finally {
        try {
            stream.close();
            isClosed = true;
        } catch (final Exception streamCloseException) {
            LOGGER.error(CONSTRUCTION_FAILED, streamCloseException);
            exception = streamCloseException;
        }
    }

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

From source file:com.cloudbees.tftwoway.Client.java

public static TrustManager[] getTrustManager() throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore store = KeyStore.getInstance("JKS");

    store.load(null);//from   w w  w .j  av a  2  s  .c o  m
    X509Certificate cacerts = loadX509Key(CACERT);
    store.setCertificateEntry("cert", cacerts);

    trustManagerFactory.init(store);

    return trustManagerFactory.getTrustManagers();
}

From source file:learn.encryption.ssl.SSLContext_Https.java

public static SSLContext getSSLContext2(String servercerfile, String clientkeyStore, String clientPass) {
    if (sslContext != null) {
        return sslContext;
    }//  w ww  .  j av  a 2s .  c o  m
    try {
        // ??, ??assets
        //InputStream inputStream = App.getInstance().getAssets().open("serverkey.cer");
        InputStream inputStream = new FileInputStream(new File(servercerfile));
        // ??
        CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");
        Certificate cer = cerFactory.generateCertificate(inputStream);
        // ?KeyStore
        KeyStore keyStore = KeyStore.getInstance("PKCS12");//eclipse?jksandroidPKCS12??
        keyStore.load(null, null);
        keyStore.setCertificateEntry("trust", cer);

        // KeyStoreTrustManagerFactory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        sslContext = SSLContext.getInstance("TLS");

        //?clientKeyStore(android??bks)
        //KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        KeyStore clientKeyStore = KeyStore.getInstance("jks");
        //clientKeyStore.load(App.getInstance().getAssets().open("clientkey.bks"), "123456".toCharArray());
        clientKeyStore.load(new FileInputStream(new File(clientkeyStore)), clientPass.toCharArray());

        // ?clientKeyStorekeyManagerFactory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(clientKeyStore, clientPass.toCharArray());

        // ?SSLContext  trustManagerFactory.getTrustManagers()
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());//new TrustManager[]{trustManagers}??
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sslContext;
}

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

@Override
protected void onHandleIntent(Intent intent) {
    if (intent.getAction().equals(stopAction)) {
        stopSelf();/* ww  w.  java  2  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:de.betterform.connector.http.ssl.BetterFORMTrustManager.java

private TrustManager[] getJavaDefaultTrustManagers()
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init((KeyStore) null);

    return trustManagerFactory.getTrustManagers();
}

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   ww w.  ja v  a2  s .c  o  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:com.screenslicer.common.LenientHttpsConfig.java

private LenientHttpsConfig() {
    AsyncHttpClientConfig configTmp = null;
    SSLContext sslContextTmp = null;
    try {//from  w w w  .j  a  v a 2  s  .co  m
        AsyncHttpClient client = new AsyncHttpClient();
        configTmp = client.getConfig();
        IOUtils.closeQuietly(client);
        client = null;

        X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(CommonUtil.class.getResourceAsStream("screenslicer.internal.cert"));
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        keyStore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert);
        KeyManagerFactory keyManager = KeyManagerFactory.getInstance("SunX509");
        keyManager.init(keyStore, null);
        TrustManagerFactory trustManager = TrustManagerFactory.getInstance("X509");
        trustManager.init(keyStore);
        sslContextTmp = SSLContext.getInstance("TLS");
        sslContextTmp.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
    } catch (Throwable t) {
    }
    config = configTmp;
    sslContext = sslContextTmp;
}

From source file:org.reficio.ws.it.util.SslTunnel.java

public void start() {
    try {/*from   www.j a  va 2  s.  c om*/
        sslContext = SSLContext.getInstance("SSLv3");
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        if (keyStore != null) {
            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
            X509KeyManager defaultKeyManager = (X509KeyManager) keyManagerFactory.getKeyManagers()[0];
            keyManagers = new KeyManager[] { defaultKeyManager };

        }
        if (trustStore != null) {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(trustStore);
            X509TrustManager defaultTrustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
            trustManagers = new TrustManager[] { defaultTrustManager };
        }

        sslContext.init(keyManagers, trustManagers, new SecureRandom());

        SSLServerSocketFactory socketFactory = sslContext.getServerSocketFactory();
        socket = socketFactory.createServerSocket();
        socket.setReuseAddress(true);
        socket.bind(new InetSocketAddress(sourcePort));
        new ServerThread(socket, run).start();
    } catch (Exception ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
}

From source file:org.apache.ftpserver.ssl.Ssl.java

/**
 * Configure secure server related properties. 
 *//*  w w  w  .j  av a2 s  .c o m*/
public void configure(Configuration conf) throws FtpException {

    try {

        // get configuration parameters
        m_keystoreFile = conf.getString("keystore-file", "./res/.keystore");
        m_keystorePass = conf.getString("keystore-password", "password");
        m_keystoreType = conf.getString("keystore-type", "JKS");
        m_keystoreAlgorithm = conf.getString("keystore-algorithm", "SunX509");
        m_sslProtocol = conf.getString("ssl-protocol", "TLS");
        m_clientAuthReqd = conf.getBoolean("client-authentication", false);
        m_keyPass = conf.getString("key-password", "password");

        // initialize keystore
        FileInputStream fin = null;
        try {
            fin = new FileInputStream(m_keystoreFile);
            m_keyStore = KeyStore.getInstance(m_keystoreType);
            m_keyStore.load(fin, m_keystorePass.toCharArray());
        } finally {
            IoUtils.close(fin);
        }

        // initialize key manager factory
        m_keyManagerFactory = KeyManagerFactory.getInstance(m_keystoreAlgorithm);
        m_keyManagerFactory.init(m_keyStore, m_keyPass.toCharArray());

        // initialize trust manager factory
        m_trustManagerFactory = TrustManagerFactory.getInstance(m_keystoreAlgorithm);
        m_trustManagerFactory.init(m_keyStore);

        // create ssl context map - the key is the 
        // SSL protocol and the value is SSLContext.
        m_sslContextMap = new HashMap();
    } catch (Exception ex) {
        m_log.fatal("Ssl.configure()", ex);
        throw new FtpException("Ssl.configure()", ex);
    }
}