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:org.openmrs.module.rheashradapter.util.GenerateORU_R01Alert.java

public void sendRequest(String msg, Encounter e)
        throws IOException, TransformerFactoryConfigurationError, TransformerException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException, KeyManagementException {
    // Get the key store that includes self-signed cert as a "trusted"
    // entry./*from w  ww  . ja v a2s. co m*/
    InputStream keyStoreStream = GenerateORU_R01Alert.class.getResourceAsStream("/truststore-prod.jks");

    // Load the keyStore

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(keyStoreStream, keystorePassword.toCharArray());
    log.info("KeyStoreStream = " + IOUtils.toString(keyStoreStream));
    keyStoreStream.close();

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);

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

    // set SSL Factory to be used for all HTTPS connections
    sslFactory = ctx.getSocketFactory();

    callQueryFacility(msg, e);

}

From source file:com.base.net.volley.toolbox.HurlStack.java

private SSLSocketFactory getDefaultSSLSocketFactory() {
    SSLSocketFactory mySSLSocketFactory = null;
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }/* w w w . j  ava 2s.  c o  m*/

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    // Install the all-trusting trust manager

    SSLContext sc;
    try {
        sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        mySSLSocketFactory = sc.getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return mySSLSocketFactory;
}

From source file:de.escidoc.core.test.sb.HttpRequester.java

/**
 * Sends request with given method and given body to given URI and returns result as String.
 *
 * @param resource String resource/*from ww  w .  j  a v a 2s .c  o m*/
 * @param method   String method
 * @param body     String body
 * @return String response
 * @throws Exception e
 */
private String requestSsl(final String resource, final String method, final String body) throws Exception {
    URL url;
    InputStream is = null;
    StringBuffer response = new StringBuffer();

    // Open Connection to given resource
    url = new URL(domain + resource);
    TrustManager[] tm = { new RelaxedX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, tm, new java.security.SecureRandom());
    SSLSocketFactory sslSF = sslContext.getSocketFactory();
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setSSLSocketFactory(sslSF);

    // Set Basic-Authentication Header
    if (securityHandle != null && !securityHandle.equals("")) {
        String encoding = new String(Base64.encodeBase64(securityHandle.getBytes(ClientBase.DEFAULT_CHARSET)));
        con.setRequestProperty("Authorization", "Basic " + encoding);
    }

    // Set request-method and timeout
    con.setRequestMethod(method.toUpperCase(Locale.ENGLISH));
    con.setReadTimeout(TIMEOUT);

    // If PUT or POST, write given body in Output-Stream
    if ((method.equalsIgnoreCase("PUT") || method.equalsIgnoreCase("POST")) && body != null) {
        con.setDoOutput(true);
        OutputStream out = con.getOutputStream();
        out.write(body.getBytes(ClientBase.DEFAULT_CHARSET));
        out.flush();
        out.close();
    }

    // Request
    is = con.getInputStream();

    // Read response
    String currentLine = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    while ((currentLine = br.readLine()) != null) {
        response.append(currentLine + "\n");
    }
    is.close();
    return response.toString();
}

From source file:org.wisdom.framework.vertx.VertxDispatcherTest.java

public void prepareHttps() throws KeyManagementException, NoSuchAlgorithmException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }//w  ww . j  a v a 2  s . c  o m

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    // Install the all-trusting trust manager
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = (hostname, session) -> true;

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

}

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

@Override
protected void onHandleIntent(Intent intent) {
    if (intent.getAction().equals(stopAction)) {
        stopSelf();/*from   ww w  .  j  ava 2 s . 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:sabina.integration.TestScenario.java

/**
 * Convenience method to use own truststore on SSL Sockets. Will default to
 * the self signed keystore provided in resources, but will respect
 * <p>//from   w ww.  jav  a 2s .com
 * -Djavax.net.ssl.keyStore=serverKeys
 * -Djavax.net.ssl.keyStorePassword=password
 * -Djavax.net.ssl.trustStore=serverTrust
 * -Djavax.net.ssl.trustStorePassword=password SSLApplication
 * <p>
 * So these can be used to specify other key/trust stores if required.
 *
 * @return an SSL Socket Factory using either provided keystore OR the
 * keystore specified in JVM params
 */
private SSLSocketFactory getSslFactory() {
    KeyStore keyStore;

    try {
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream fis = new FileInputStream(getTrustStoreLocation());
        keyStore.load(fis, getTrustStorePassword().toCharArray());
        fis.close();

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, tmf.getTrustManagers(), null);
        return ctx.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.mule.transport.ldap.LdapSConnector.java

protected void setupSSL() throws InitialisationException {
    try {/*w  w  w.  j  a va 2 s.  c  o m*/
        logger.debug("trustAll: " + trustAll);
        logger.debug("trustStore: " + trustStore);
        if (trustAll) {
            final SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, trustAll ? TrustAllCertsManager.getTrustAllCertsManager() : null, null);

            // certificate_unknown

            if (startTLS) {
                ssf = new LDAPJSSEStartTLSFactory(context.getSocketFactory());
            } else {
                ssf = new LDAPJSSESecureSocketFactory(context.getSocketFactory());
            }

        } else {
            if (org.apache.commons.lang.StringUtils.isEmpty(trustStore)) {
                throw new InitialisationException(
                        new IllegalArgumentException(
                                "Either trustAll value must be true or the trustStore parameter must be set"),
                        this);
            }

            final File trustStoreFile = new File(trustStore);

            if (!trustStoreFile.exists() || !trustStoreFile.canRead()) {
                throw new InitialisationException(new IllegalArgumentException("truststore file "
                        + trustStoreFile.getAbsolutePath() + " do not exist or is not readable"), this);
            }

            System.setProperty("javax.net.ssl.trustStore", trustStoreFile.getAbsolutePath());
            // System.setProperty (
            // "javax.net.ssl.keyStore",trustStoreFile.getAbsolutePath() );
            // System.setProperty ( "javax.net.ssl.keyStorePassword",
            // "changeit" );

            logger.debug("truststore set to " + trustStoreFile.getAbsolutePath());
            if (startTLS) {
                ssf = new LDAPJSSEStartTLSFactory();
            } else {
                ssf = new LDAPJSSESecureSocketFactory();
            }
        }

    } catch (final KeyManagementException e) {
        throw new InitialisationException(e, this);
    } catch (final NoSuchAlgorithmException e) {
        throw new InitialisationException(e, this);
    }

    // super.setSsf(ssf);
}

From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java

public ConnectionHandler() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, KeyManagementException {

    InputStream keyStoreStream = getClass().getResourceAsStream("/web/module/resources/truststore.jks");

    // Load the keyStore
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(keyStoreStream, "Jembi#123".toCharArray());
    keyStoreStream.close();/*from   ww w  .  jav  a  2  s  .c  om*/

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);

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

    // set SSL Factory to be used for all HTTPS connections
    sslFactory = ctx.getSocketFactory();
    setImplementationId();
}

From source file:com.appdynamics.monitors.mongo.MongoDBMonitor.java

private SSLSocketFactory getSocketFactoryFromPEM(String filePath) throws Exception {
    Security.addProvider(new BouncyCastleProvider());

    PEMParser pemParser = new PEMParser(new FileReader(getConfigFilename(filePath)));
    pemParser.readObject();//from   www  .ja  va 2  s . c o  m
    PemObject pemObject = pemParser.readPemObject();
    pemParser.close();

    X509CertificateHolder holder = new X509CertificateHolder(pemObject.getContent());
    X509Certificate bc = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder);

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", bc);

    TrustManager trustManager = TrustManagerUtils.getDefaultTrustManager(keyStore);
    SSLContext sslContext = SSLContextUtils.createSSLContext("TLS", null, trustManager);

    return sslContext.getSocketFactory();
}

From source file:com.saylor.harrison.opustestround2.audio.WebSocketUploader.java

/**
 * Trust server//  w  w  w  .ja va 2 s  .  com
 *
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
private void trustServer() throws KeyManagementException, NoSuchAlgorithmException, IOException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] certs = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

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

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };
    SSLContext sslContext = null;
    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, certs, new java.security.SecureRandom());
    SSLSocketFactory factory = sslContext.getSocketFactory();
    this.setSocket(factory.createSocket());
}