Example usage for javax.net.ssl SSLContext getSocketFactory

List of usage examples for javax.net.ssl SSLContext getSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getSocketFactory.

Prototype

public final SSLSocketFactory getSocketFactory() 

Source Link

Document

Returns a SocketFactory object for this context.

Usage

From source file:at.diamonddogs.net.SSLHelper.java

private void makeAllTrustManagerForJava() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, getAllTrustingManager(), new java.security.SecureRandom());
    SSL_FACTORY_JAVA = sslCtx.getSocketFactory();
}

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 {/*  ww w.ja  v a  2 s  .co m*/
        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);
    }
}

From source file:com.esri.geoevent.test.performance.bds.BdsEventConsumer.java

private void trustAll() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/*from   w  w w  .  j  av a  2s .  c  o  m*/
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (GeneralSecurityException e) {
        System.out.println("Oops");
    }
}

From source file:net.jmhertlein.mcanalytics.console.gui.LoginPane.java

@FXML
public void onLoginButtonPressed(ActionEvent event) {
    HostEntry selected = hostList.getSelectionModel().getSelectedItem();
    if (selected == null)
        return;/*from w ww  .jav  a  2  s  .  c  om*/

    try {
        SSLContext ctx = SSLUtil.buildClientContext(trust);
        SSLSocket raw = (SSLSocket) ctx.getSocketFactory().createSocket(selected.getUrl(), selected.getPort());
        raw.setWantClientAuth(true);
        try {
            System.out.println("Starting handshake...");
            raw.startHandshake();
        } catch (SSLException ssle) {
            if (ssle.getCause() instanceof UntrustedCertificateException) {
                System.out.println("Got the correct exception");
                UntrustedCertificateException uce = (UntrustedCertificateException) ssle.getCause();
                CertTrustPromptDialog dlg = new CertTrustPromptDialog(trust,
                        (X509Certificate) uce.getChain()[0]);
                dlg.showAndWait();
                System.out.println("DIALOG RETURNED");
            }
            return;
        }

        PrintWriter out = new PrintWriter(raw.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(raw.getInputStream()));
        APISocket sock = new APISocket(out, in);
        app.setAPISocket(sock);
        sock.startListener();

        //handle authentication
        boolean hasCert = false;
        FutureRequest<AuthenticationResult> login;
        if (trust.isCertificateEntry(selected.getUrl())) {
            try {
                ((X509Certificate) trust.getCertificate(selected.getUrl())).checkValidity();
                hasCert = true;
            } catch (CertificateExpiredException | CertificateNotYetValidException ex) {
                Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        System.out.println("Has cert: " + hasCert);
        KeyPair newPair = null;
        String username;

        if (hasCert) {
            username = SSLUtil.getCNs((X509Certificate) trust.getCertificate(selected.getUrl())).iterator()
                    .next();
            login = sock.submit(new AuthenticationRequest(username));
            System.out.println("Logging in w/ cert. CN: " + username + ", URL: " + selected.getUrl());
        } else if (rememberLoginBox.isSelected()) {
            newPair = SSLUtil.newECDSAKeyPair();
            username = usernameField.getText();
            PKCS10CertificationRequest csr = SSLUtil.newCertificateRequest(
                    SSLUtil.newX500Name(username, selected.getUrl(), "mcanalytics"), newPair);
            login = sock
                    .submit(new AuthenticationRequest(usernameField.getText(), passwordField.getText(), csr));
            System.out.println("Logging in with: " + usernameField.getText() + " + " + passwordField.getText()
                    + " and requesting a cert.");
        } else {
            username = usernameField.getText();
            login = sock.submit(new AuthenticationRequest(username, passwordField.getText()));
            System.out.println("Logging in with: " + username + " + " + passwordField.getText());
        }

        try {
            boolean success = login.get().getSuccess();
            if (success) {
                System.out.println("Login successful");
                if (login.get().hasCertificate()) {
                    trust.setCertificateEntry(selected.getUrl(), login.get().getCert());
                    trust.setKeyEntry(selected.getUrl() + "-private", newPair.getPrivate(), new char[0],
                            new Certificate[] { login.get().getCert(), login.get().getCA() });
                    System.out.println("Stored a trusted cert from server.");
                }
            } else {
                System.out.println("Login failed.");
                Dialog dlg = new Dialog();
                dlg.setTitle("Login Failed");
                dlg.setContentText("Could not login- invalid login credentials.");
                dlg.showAndWait();
                return;
            }
        } catch (InterruptedException | ExecutionException | KeyStoreException ex) {
            Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex);
            Dialogs.showMessage("Connection Error", "Connection Error", ex.getMessage(), ex.toString());
            System.out.println("Login error.");
            return;
        }
        //auth done

        Stage window = (Stage) loginButton.getScene().getWindow();
        window.setScene(new Scene(new ChartPane(username, sock)));
        window.show();
    } catch (IOException | KeyStoreException ex) {
        Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex);
        Dialog dlg = new Dialog();
        dlg.setTitle("Connection Error");
        dlg.setContentText(ex.getMessage());
        dlg.showAndWait();
        System.out.println("Login error.");
        return;
    }
}

From source file:at.diamonddogs.net.SSLHelper.java

/**
 * Register a keystore with SSL (JAVA)/*from  w ww.j a va  2s  .  c o  m*/
 * 
 * @param c
 *            a {@link Context}
 * @param resourceId
 *            the resource id of the keystore
 * @param password
 *            the password of the keystore
 * @return true on success, false otherwise
 */
public boolean initSSLFactoryJava(Context c, int resourceId, String password) {
    try {
        if (c == null || resourceId == -1 || password == null) {
            LOGGER.info("No keystore specified, using alltrust");
            makeAllTrustManagerForJava();
            return true;
        } else {
            KeyStore store = getKeyStore(c, resourceId, password);
            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(store);
            SSLContext sslCtx = SSLContext.getInstance("TLS");
            sslCtx.init(null, tmf.getTrustManagers(), null);
            SSL_FACTORY_JAVA = sslCtx.getSocketFactory();
            sslState.trustAll = false;
            return true;
        }
    } catch (Throwable tr) {
        LOGGER.warn("Error initializing SSLFactoryJava", tr);
        try {
            makeAllTrustManagerForJava();
            sslState.tr = tr;
            return true;
        } catch (Throwable tr1) {
            sslState.tr1 = tr1;
            sslState.sslOk = false;
            LOGGER.warn("Error trusting all certs, no ssl connection possible", tr);
        }
        return false;
    }
}

From source file:com.spotify.sshagenttls.CertHttpsHandler.java

public void handle(final HttpsURLConnection conn) {
    final CertKey certKey;
    try {/*  w  ww .j a v a  2s  .c  o  m*/
        certKey = createCertKey();
    } catch (IOException | GeneralSecurityException e) {
        if (failOnCertError) {
            throw new RuntimeException(e);
        } else {
            LOG.warn("Error when setting up client certificates fromPaths {}. Error was '{}'. "
                    + "No cert will be sent with request.", getCertSource(), e.toString());
            LOG.debug("full exception fromPaths setting up ClientCertificate follows", e);
            return;
        }
    }

    final Certificate cert = certKey.cert();
    final PrivateKey key = certKey.key();

    // Generate a keystore password.
    // Do all this locally to not make copies of the password in memory.
    final SecureRandom random = new SecureRandom();
    final int numBytes = 60;
    final char[] keyStorePassword = new char[numBytes];
    for (int i = 0; i < numBytes; i++) {
        // Only use ASCII characters for the password. The corresponding integer range is [32, 126].
        keyStorePassword[i] = (char) (random.nextInt(95) + 32);
    }

    try {
        // We're creating a keystore in memory and putting the cert & key into it.
        // The keystore needs a password when we put the key into it, even though it's only going to
        // exist for the lifetime of the process. So we just have some random password that we use.

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("client", cert);
        keyStore.setKeyEntry("key", key, keyStorePassword, new Certificate[] { cert });

        // build an SSLContext based on our keystore, and then get an SSLSocketFactory fromPaths that
        final SSLContext sslContext = SSLContexts.custom().useProtocol("TLS")
                .loadKeyMaterial(keyStore, keyStorePassword).build();

        // Clear out arrays that had password
        Arrays.fill(keyStorePassword, '\0');

        conn.setSSLSocketFactory(sslContext.getSocketFactory());
    } catch (CertificateException | IOException | NoSuchAlgorithmException | KeyStoreException
            | UnrecoverableKeyException | KeyManagementException e) {
        // so many dumb ways to die. see https://www.youtube.com/watch?v=IJNR2EpS0jw for more.
        throw new RuntimeException(e);
    }
}

From source file:com.mytwitter.Network.NetworkHelper.java

/**
 * Create a trust manager that does not validate SSL certificate chains.
 *///w  w  w  .  j  a va 2  s. co  m
public void trustAllHosts() {

    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

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

    // Install the all-trusting trust manager
    try {
        // Backup the current SSL socket factory
        defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
        // Install our all trusting manager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.indiana.d2i.sloan.ui.LoginSuccessAction.java

private boolean disableSSL() {
    // Create empty HostnameVerifier
    HostnameVerifier hv = new HostnameVerifier() {
        public boolean verify(String urlHostName, SSLSession session) {
            return true;
        }/*from  w ww. j  a v a 2 s.  c o m*/
    };

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    // install all-trust manager
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory sslSocketFactory = sc.getSocketFactory();
        HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        return true;
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
        addActionError(e.getMessage());
        return false;
    } catch (KeyManagementException e) {
        logger.error(e.getMessage(), e);
        addActionError(e.getMessage());
        return false;
    }
}

From source file:org.eclipse.mylyn.internal.commons.net.PollingSslProtocolSocketFactory.java

public PollingSslProtocolSocketFactory() {
    KeyManager[] keymanagers = null;
    if (System.getProperty(KEY_STORE) != null && System.getProperty(KEY_STORE_PASSWORD) != null) {
        try {//from   www. j av a  2s . c  om
            String type = System.getProperty(KEY_STORE_TYPE, KeyStore.getDefaultType());
            KeyStore keyStore = KeyStore.getInstance(type);
            char[] password = System.getProperty(KEY_STORE_PASSWORD).toCharArray();
            keyStore.load(new FileInputStream(System.getProperty(KEY_STORE)), password);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, password);
            keymanagers = keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            CommonsNetPlugin.log(IStatus.ERROR, "Could not initialize keystore", e); //$NON-NLS-1$
        }
    }

    hasKeyManager = keymanagers != null;

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL"); //$NON-NLS-1$
        sslContext.init(keymanagers, new TrustManager[] { new TrustAllTrustManager() }, null);
        this.socketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        CommonsNetPlugin.log(IStatus.ERROR, "Could not initialize SSL context", e); //$NON-NLS-1$
    }
}

From source file:ddf.catalog.source.opensearch.SecureRemoteConnectionImpl.java

/**
 * Creates a new SSLSocketFactory from a truststore and keystore. This is used during SSL
 * communications with the server.//from  ww w.j a  va 2s .  co m
 * 
 * @param trustStoreLoc
 *            File path to the truststore.
 * @param trustStorePass
 *            Password to the truststore.
 * @param keyStoreLoc
 *            File path to the keystore.
 * @param keyStorePass
 *            Password to the keystore.
 * @return new SSLSocketFactory instance containing the trust and key stores.
 * @throws KeyStoreException
 * @throws IOException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 * @throws KeyManagementException
 */
public SSLSocketFactory createSocket(String trustStoreLoc, String trustStorePass, String keyStoreLoc,
        String keyStorePass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    String methodName = "createSocket";
    LOGGER.debug("ENTERING: " + methodName);

    LOGGER.debug("trustStoreLoc = " + trustStoreLoc);
    FileInputStream trustFIS = new FileInputStream(trustStoreLoc);
    LOGGER.debug("keyStoreLoc = " + keyStoreLoc);
    FileInputStream keyFIS = new FileInputStream(keyStoreLoc);

    // truststore stuff
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        LOGGER.debug("Loading trustStore");
        trustStore.load(trustFIS, trustStorePass.toCharArray());
    } finally {
        IOUtils.closeQuietly(trustFIS);
    }

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    LOGGER.debug("trust manager factory initialized");

    // keystore stuff
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        LOGGER.debug("Loading keyStore");
        keyStore.load(keyFIS, keyStorePass.toCharArray());
    } finally {
        IOUtils.closeQuietly(keyFIS);
    }
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, keyStorePass.toCharArray());
    LOGGER.debug("key manager factory initialized");

    // ssl context
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    LOGGER.debug("EXITING: " + methodName);

    return sslCtx.getSocketFactory();
}