Example usage for javax.net.ssl SSLContext getInstance

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

Introduction

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

Prototype

public static SSLContext getInstance(String protocol) throws NoSuchAlgorithmException 

Source Link

Document

Returns a SSLContext object that implements the specified secure socket protocol.

Usage

From source file:eu.europa.ec.markt.dss.validation.https.SimpleProtocolSocketFactory.java

private SSLContext createEasySSLContext() {
    try {/*  ww  w .  j  a v a 2s.c om*/
        SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { new OptimistTrustManager() }, null);
        return context;
    } catch (Exception e) {
        LOG.severe(e.getMessage());
        throw new HttpClientError(e.toString());
    }
}

From source file:com.iiordanov.tigervnc.rfb.CSecurityTLS.java

private void initGlobal() {
    try {//  w  w  w. j av a  2s  .  c om
        SSLSocketFactory sslfactory;
        SSLContext ctx = SSLContext.getInstance("TLS");

        if (anon) {
            ctx.init(null, null, null);
        } else {
            TrustManager[] myTM = new TrustManager[] { new MyX509TrustManager() };
            ctx.init(null, myTM, null);
        }

        sslfactory = ctx.getSocketFactory();
        try {
            ssl = (SSLSocket) sslfactory.createSocket(CConnection.sock,
                    CConnection.sock.getInetAddress().getHostName(), CConnection.sock.getPort(), true);
            ssl.setTcpNoDelay(true);
        } catch (java.io.IOException e) {
            throw new Exception(e.toString());
        }

        if (anon) {
            String[] supported;
            ArrayList<String> enabled = new ArrayList<String>();

            supported = ssl.getSupportedCipherSuites();

            for (int i = 0; i < supported.length; i++) {
                //Log.e("SUPPORTED CIPHERS", supported[i]);
                if (supported[i].matches("TLS_DH_anon.*"))
                    enabled.add(supported[i]);
            }

            if (enabled.size() == 0)
                throw new Exception("Your device lacks support for ciphers necessary for this encryption mode "
                        + "(Anonymous Diffie-Hellman ciphers). "
                        + "This is a known issue with devices running Android 2.2.x and older. You can "
                        + "work around this by using VeNCrypt with x509 certificates instead.");

            ssl.setEnabledCipherSuites(enabled.toArray(new String[0]));
        } else {
            ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites());
        }

        ssl.setEnabledProtocols(ssl.getSupportedProtocols());
        ssl.addHandshakeCompletedListener(new MyHandshakeListener());
    } catch (java.security.GeneralSecurityException e) {
        vlog.error("TLS handshake failed " + e.toString());
        return;
    }
}

From source file:de.vanita5.twittnuker.util.net.ssl.TwidereSSLSocketFactory.java

private TwidereSSLSocketFactory(final Context context, final boolean ignoreSSLErrors)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    this.context = context;
    this.ignoreSSLErrors = ignoreSSLErrors;
    final TrustManager[] tm = { new TrustAllX509TrustManager() };
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, tm, null);//from   w  w w. j  a  v a2 s .c  om
    final X509HostnameVerifier hostnameVerifier = new TwidereHostnameVerifier(context, ignoreSSLErrors);
    delegated = new HostResolvedSSLConnectionSocketFactory(sslContext, hostnameVerifier);
}

From source file:edu.gmu.isa681.server.Server.java

/**
 * Creates a TLS server socket factory using the key store and key store password provided to the JVM at runtime.
 * @return/*  www  . j  a va 2  s  .c  om*/
 * @throws GeneralSecurityException If an error occurs while creating the TLS factory.
 * @throws IOException If an error occurs while reading the key store.
 * 
 * Adapted from Oracle JSSE docs.
 */
private static SSLServerSocketFactory getSSLServerSocketFactory() throws GeneralSecurityException, IOException {
    FileInputStream fis = null;
    try {
        SSLServerSocketFactory ssf = null;
        // set up key manager to do server authentication
        SSLContext ctx = SSLContext.getInstance("TLS");
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        KeyStore ks = KeyStore.getInstance("JKS");

        String keyStore = System.getProperty("javax.net.ssl.keyStore");
        String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");

        fis = new FileInputStream(keyStore);
        ks.load(fis, keyStorePassword.toCharArray());

        kmf.init(ks, keyStorePassword.toCharArray());
        ctx.init(kmf.getKeyManagers(), null, null);

        ssf = ctx.getServerSocketFactory();
        return ssf;

    } finally {
        Utils.closeQuitely(fis);
    }
}

From source file:com.wisdombud.right.client.common.HttpKit.java

private static SSLSocketFactory initSSLSocketFactory() {
    try {/*w w  w  .  j  a v a 2 s .  c  om*/
        final TrustManager[] tm = { new HttpKit().new TrustAnyTrustManager() };
        final SSLContext sslContext = SSLContext.getInstance("TLS"); // ("TLS",
        // "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        return sslContext.getSocketFactory();
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.camel.component.solr.JettySolrFactory.java

private static void installAllTrustingClientSsl()
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

    // // Create a trust manager that does not validate certificate chains
    final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/*from www.ja  v a 2s.  c  o  m*/
        public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
        }

        @Override
        public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    SSLContext.setDefault(sslContext);

    // // Install the all-trusting trust manager
    // final SSLContext sslContext = SSLContext.getInstance( "SSL" );
    // sslContext.init( null, trustAllCerts, new
    // java.security.SecureRandom() );
    // // Create an ssl socket factory with our all-trusting manager
    // final SSLSocketFactory sslSocketFactory =
    // sslContext.getSocketFactory();
    // HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
}

From source file:client.authz.Configuration.java

/**
 * If this is a https authServerUrl and noCertCheck is true, create an SSLContext that uses
 * an X509TrustManager that allows any certificate.
 * @return SSLContext with all trusting TrustManager if noCertCheck is true, null otherwise
 *///from   w  ww  .  ja v a 2  s. com
public SSLContext getSSLContext() {
    SSLContext sslContext = null;
    if (authServerUrl.startsWith("https") && noCertCheck) {
        try {
            // Install a TrustManager that ignores certificate checks
            sslContext = SSLContext.getInstance("TLS");
            TrustManager[] trustManagers = { new TrustAllManager() };
            sslContext.init(null, trustManagers, new SecureRandom());
        } catch (Exception e) {
            throw new IllegalStateException("Failed to create HttpsClient", e);
        }
    }

    return sslContext;
}

From source file:com.cloudhopper.httpclient.util.HttpSender.java

static public Response postXml(String url, String username, String password, String requestXml)
        throws Exception {
    ///*  ww  w.j  a v  a2s .c o  m*/
    // trust any SSL connection
    //
    TrustManager easyTrustManager = new X509TrustManager() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", sf, 443);

    //SchemeRegistry sr = new SchemeRegistry();
    //sr.register(http);
    //sr.register(https);

    // create and initialize scheme registry
    //SchemeRegistry schemeRegistry = new SchemeRegistry();
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    //ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    //cm.setMaxTotalConnections(1);

    DefaultHttpClient client = new DefaultHttpClient();

    client.getConnectionManager().getSchemeRegistry().register(https);

    HttpPost post = new HttpPost(url);

    StringEntity postEntity = new StringEntity(requestXml, "ISO-8859-1");
    postEntity.setContentType("text/xml; charset=\"ISO-8859-1\"");
    post.addHeader("SOAPAction", "\"\"");
    post.setEntity(postEntity);

    long start = System.currentTimeMillis();

    client.getCredentialsProvider().setCredentials(new AuthScope(null, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpResponse httpResponse = client.execute(post, localcontext);
    HttpEntity responseEntity = httpResponse.getEntity();

    Response rsp = new Response();

    // set the status line and reason
    rsp.statusCode = httpResponse.getStatusLine().getStatusCode();
    rsp.statusLine = httpResponse.getStatusLine().getReasonPhrase();

    // get an input stream
    rsp.body = EntityUtils.toString(responseEntity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    client.getConnectionManager().shutdown();

    return rsp;
}

From source file:io.wcm.caravan.commons.httpclient.impl.helpers.CertificateLoader.java

/**
 * Build SSL Socket factory.//from w  ww  .j  a va 2 s.c  om
 * @param config Http client configuration
 * @return SSL socket factory.
 * @throws IOException
 * @throws GeneralSecurityException
 */
public static SSLContext buildSSLContext(HttpClientConfig config) throws IOException, GeneralSecurityException {

    KeyManagerFactory kmf = null;
    if (isSslKeyManagerEnabled(config)) {
        kmf = getKeyManagerFactory(config.getKeyStorePath(), new StoreProperties(config.getKeyStorePassword(),
                config.getKeyManagerType(), config.getKeyStoreType()));
    }
    TrustManagerFactory tmf = null;
    if (isSslTrustStoreEnbaled(config)) {
        StoreProperties storeProperties = new StoreProperties(config.getTrustStorePassword(),
                config.getTrustManagerType(), config.getTrustStoreType());
        tmf = getTrustManagerFactory(config.getTrustStorePath(), storeProperties);
    }

    SSLContext sslContext = SSLContext.getInstance(config.getSslContextType());
    sslContext.init(kmf != null ? kmf.getKeyManagers() : null, tmf != null ? tmf.getTrustManagers() : null,
            null);

    return sslContext;
}

From source file:Main.java

@SuppressWarnings("resource")
public static String post(String targetUrl, Map<String, String> params, String file, byte[] data) {
    Logd(TAG, "Starting post...");
    String html = "";
    Boolean cont = true;/*from  w w w  . j  a  va  2  s  .c  o  m*/
    URL url = null;
    try {
        url = new URL(targetUrl);
    } catch (MalformedURLException e) {
        Log.e(TAG, "Invalid url: " + targetUrl);
        cont = false;
        throw new IllegalArgumentException("Invalid url: " + targetUrl);
    }
    if (cont) {
        if (!targetUrl.startsWith("https") || gVALID_SSL.equals("true")) {
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        } else {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // TODO Auto-generated method stub
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                    // TODO Auto-generated method stub
                }
            } };
            // Install the all-trusting trust manager
            SSLContext sc;
            try {
                sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                // Create all-trusting host name verifier
                HostnameVerifier allHostsValid = new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                };
                // Install the all-trusting host verifier
                HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
            } catch (NoSuchAlgorithmException e) {
                Logd(TAG, "Error: " + e.getLocalizedMessage());
            } catch (KeyManagementException e) {
                Logd(TAG, "Error: " + e.getLocalizedMessage());
            }
        }
        Logd(TAG, "Filename: " + file);
        Logd(TAG, "URL: " + targetUrl);
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        String pathToOurFile = file;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024;
        try {
            connection = (HttpURLConnection) url.openConnection();
            // Allow Inputs & Outputs
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            //Don't use chunked post requests (nginx doesn't support requests without a Content-Length header)
            //connection.setChunkedStreamingMode(1024);
            // Enable POST method
            connection.setRequestMethod("POST");
            setBasicAuthentication(connection, url);
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            outputStream = new DataOutputStream(connection.getOutputStream());
            //outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> param = iterator.next();
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                outputStream.writeBytes("Content-Disposition: form-data;" + "name=\"" + param.getKey() + "\""
                        + lineEnd + lineEnd);
                outputStream.write(param.getValue().getBytes("UTF-8"));
                outputStream.writeBytes(lineEnd);
            }
            String connstr = null;
            if (!file.equals("")) {
                FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile));
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"" + pathToOurFile + "\""
                        + lineEnd;
                outputStream.writeBytes(connstr);
                outputStream.writeBytes(lineEnd);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                // Read file
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                Logd(TAG, "File length: " + bytesAvailable);
                try {
                    while (bytesRead > 0) {
                        try {
                            outputStream.write(buffer, 0, bufferSize);
                        } catch (OutOfMemoryError e) {
                            e.printStackTrace();
                            html = "Error: outofmemoryerror";
                            return html;
                        }
                        bytesAvailable = fileInputStream.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                    }
                } catch (Exception e) {
                    Logd(TAG, "Error: " + e.getLocalizedMessage());
                    html = "Error: Unknown error";
                    return html;
                }
                outputStream.writeBytes(lineEnd);
                fileInputStream.close();
            } else if (data != null) {
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"tmp\"" + lineEnd;
                outputStream.writeBytes(connstr);
                outputStream.writeBytes(lineEnd);
                bytesAvailable = data.length;
                Logd(TAG, "File length: " + bytesAvailable);
                try {
                    outputStream.write(data, 0, data.length);
                } catch (OutOfMemoryError e) {
                    e.printStackTrace();
                    html = "Error: outofmemoryerror";
                    return html;
                } catch (Exception e) {
                    Logd(TAG, "Error: " + e.getLocalizedMessage());
                    html = "Error: Unknown error";
                    return html;
                }
                outputStream.writeBytes(lineEnd);
            }
            outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // Responses from the server (code and message)
            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();
            Logd(TAG, "Server Response Code " + serverResponseCode);
            Logd(TAG, "Server Response Message: " + serverResponseMessage);
            if (serverResponseCode == 200) {
                InputStreamReader in = new InputStreamReader(connection.getInputStream());
                BufferedReader br = new BufferedReader(in);
                String decodedString;
                while ((decodedString = br.readLine()) != null) {
                    html += decodedString;
                }
                in.close();
            }
            outputStream.flush();
            outputStream.close();
            outputStream = null;
        } catch (Exception ex) {
            // Exception handling
            html = "Error: Unknown error";
            Logd(TAG, "Send file Exception: " + ex.getMessage());
        }
    }
    if (html.startsWith("success:"))
        Logd(TAG, "Server returned: success:HIDDEN");
    else
        Logd(TAG, "Server returned: " + html);
    return html;
}