Example usage for org.apache.http.conn.ssl SSLSocketFactory SSLSocketFactory

List of usage examples for org.apache.http.conn.ssl SSLSocketFactory SSLSocketFactory

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLSocketFactory SSLSocketFactory.

Prototype

public SSLSocketFactory(final SSLContext sslContext) 

Source Link

Usage

From source file:net.shirayu.android.WlanLogin.MyHttpClient.java

public MyHttpClient(KeyStore certstore)
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
    HttpParams params = new BasicHttpParams();
    SSLSocketFactory sf = new SSLSocketFactory(certstore);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", sf, 443));
    ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, schemeRegistry);
    client = new DefaultHttpClient(ccm, params);
    client.setCredentialsProvider(this);
    client.addResponseInterceptor(this);
}

From source file:org.gw2InfoViewer.factories.HttpsConnectionFactory.java

public static HttpClient getHttpsClient(byte[] sslCertificateBytes) {
    DefaultHttpClient httpClient;//from w  ww  . j ava  2 s  .  c o  m
    Certificate[] sslCertificate;

    httpClient = new DefaultHttpClient();
    try {
        sslCertificate = convertByteArrayToCertificate(sslCertificateBytes);

        TrustManagerFactory tf = TrustManagerFactory.getInstance("X509");
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null);
        for (int i = 0; i < sslCertificate.length; i++) {
            ks.setCertificateEntry("StartCom" + i, sslCertificate[i]);
        }

        tf.init(ks);
        TrustManager[] tm = tf.getTrustManagers();

        SSLContext sslCon = SSLContext.getInstance("SSL");
        sslCon.init(null, tm, new SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(ks);
        Scheme sch = new Scheme("https", 443, socketFactory);

        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException | UnrecoverableKeyException ex) {
        Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
    }

    return httpClient;
}

From source file:org.wso2.emm.agent.proxy.clients.OAuthSSLClient.java

@Override
public HttpClient getHttpClient() throws IDPTokenManagerException {
    HttpClient client = null;//from w ww .  ja v  a  2s.c om
    InputStream inStream = null;
    try {
        if (Constants.SERVER_PROTOCOL.equalsIgnoreCase("https://")) {
            KeyStore localTrustStore = KeyStore.getInstance("BKS");
            inStream = IdentityProxy.getInstance().getContext().getResources().openRawResource(R.raw.trust);
            localTrustStore.load(inStream, Constants.TRUSTSTORE_PASSWORD.toCharArray());

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), Constants.HTTP));
            SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore);
            sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            schemeRegistry.register(new Scheme("https", sslSocketFactory, Constants.HTTPS));
            HttpParams params = new BasicHttpParams();
            ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);

            client = new DefaultHttpClient(connectionManager, params);

        } else {
            client = new DefaultHttpClient();
        }

    } catch (KeyStoreException e) {
        String errorMsg = "Error occurred while accessing keystore.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "Error occurred while loading certificate.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Error occurred while due to mismatch of defined algorithm.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (UnrecoverableKeyException e) {
        String errorMsg = "Error occurred while accessing keystore.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (KeyManagementException e) {
        String errorMsg = "Error occurred while accessing keystore.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "Error occurred while loading trust store. ";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } finally {
        StreamHandlerUtil.closeInputStream(inStream, TAG);
    }
    return client;
}

From source file:eu.trentorise.smartcampus.ac.network.HttpsClientBuilder.java

private static HttpClient getAcceptAllHttpClient(HttpParams inParams) {
    HttpClient client = null;//w  w  w  .  j a va2s. c  om

    HttpParams params = inParams != null ? inParams : new BasicHttpParams();

    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

        // IMPORTANT: use CustolSSLSocketFactory for 2.2
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(trustStore);
        if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.FROYO) {
            sslSocketFactory = new CustomSSLSocketFactory(trustStore);
        }

        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        registry.register(new Scheme("https", sslSocketFactory, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        client = new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        client = new DefaultHttpClient(params);
    }

    return client;
}

From source file:ac.uk.diamond.sample.HttpClientTest.Utils.java

/**
 * Create a connection manager that trusts any certificate.
 *//*from w w  w. j  a va2  s  .c  om*/
static SSLSocketFactory getAnyCertManager() {
    try {
        SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] aChain, String aAuthType) throws CertificateException {
                return true;
            }
        });
        return sf;
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.cwru.apo.TrustAPOHttpClient.java

private SSLSocketFactory newSslSocketFactory() {
    try {//from  w ww .ja va 2s .  c  om
        // Get an instance of the Bouncy Castle KeyStore format
        KeyStore trusted = KeyStore.getInstance("BKS");
        // Get the raw resource, which contains the keystore with
        // your trusted certificates (root and any intermediate certs)
        InputStream in = context.getResources().openRawResource(R.raw.keystore);
        try {
            // Initialize the keystore with the provided trusted certificates
            // Also provide the password of the keystore
            trusted.load(in, "mysecret".toCharArray());
        } finally {
            in.close();
        }
        // Pass the keystore to the SSLSocketFactory. The factory is responsible
        // for the verification of the server certificate.
        SSLSocketFactory sf = new SSLSocketFactory(trusted);
        // Hostname verification from certificate
        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
        sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        return sf;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

From source file:edu.washington.iam.tools.IamConnectionManager.java

public IamConnectionManager(String caFile, String certFile, String keyFile) {
    log.debug("create connection manager");
    caFilename = caFile;//from  ww  w. j av  a2s  .co m
    certFilename = certFile;
    keyFilename = keyFile;
    String protocol = "https";
    int port = 443;

    initManagers();

    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(keyManagers, trustManagers, null);
        socketFactory = new SSLSocketFactory(ctx);
        Scheme scheme = new Scheme(protocol, socketFactory, port);
        schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(scheme);

        log.debug("create conn mgr");
        connectionManager = new ThreadSafeClientConnManager(new BasicHttpParams(), schemeRegistry);

    } catch (Exception e) {
        log.error("sf error: " + e);
    }
}

From source file:org.authme.android.util.AuthMeHttpClient.java

private SSLSocketFactory newSslSocketFactory() {
    try {/*from  ww  w.  ja  va2 s  .c  om*/
        // Get an instance of the Bouncy Castle KeyStore format
        KeyStore trusted = KeyStore.getInstance("BKS");

        // Could probably load the main keystore and then append, but this works
        trusted.load(null, null);
        InputStream is = context.getResources().openRawResource(R.raw.cacert_root);
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X509");
        Certificate certificate = certificateFactory.generateCertificate(is);
        trusted.setCertificateEntry("CACertRoot", certificate);

        // Now continue on using this keystore

        SSLSocketFactory sf = new SSLSocketFactory(trusted);
        // Hostname verification from certificate
        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
        sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        return sf;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

From source file:com.phonty.improved.PhontyHttpClient.java

private SSLSocketFactory newSslSocketFactory() {
    try {//www .  j  a v a 2 s. c  o m
        // Get an instance of the Bouncy Castle KeyStore format
        KeyStore trusted = KeyStore.getInstance("BKS");
        // Get the raw resource, which contains the keystore with
        // your trusted certificates (root and any intermediate certs)
        InputStream in = context.getResources().openRawResource(R.raw.keystore);
        try {
            // Initialize the keystore with the provided trusted certificates
            // Also provide the password of the keystore
            trusted.load(in, "pqoeponkjlcnvkjenenobnervoerovneokrnvoie".toCharArray());
        } finally {
            in.close();
        }
        // Pass the keystore to the SSLSocketFactory. The factory is responsible
        // for the verification of the server certificate.
        SSLSocketFactory sf = new SSLSocketFactory(trusted);
        // Hostname verification from certificate
        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
        sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        return sf;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

From source file:org.commonjava.indy.httprox.ProxyHttpsDownloadTgzTest.java

protected File getDownloadedFile(String url, boolean withCACert, String user, String pass) throws Exception {
    CloseableHttpClient client;// ww w .j a  va 2  s. c om

    if (withCACert) {
        File jks = new File(etcDir, "ssl/ca.jks");
        KeyStore trustStore = getTrustStore(jks);
        SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
        client = proxiedHttp(user, pass, socketFactory);
    } else {
        client = proxiedHttp(user, pass);
    }

    HttpGet get = new HttpGet(url);
    CloseableHttpResponse response = null;

    InputStream stream = null;
    try {
        response = client.execute(get, proxyContext(user, pass));
        StatusLine status = response.getStatusLine();
        System.out.println("status >>>> " + status);

        if (status.getStatusCode() == 404) {
            return null;
        }

        stream = response.getEntity().getContent();
        File file = getTemp().newFile();
        FileOutputStream fileOutputStream = new FileOutputStream(file);
        IOUtils.copy(stream, fileOutputStream);
        fileOutputStream.close();

        return file;
    } finally {
        IOUtils.closeQuietly(stream);
        HttpResources.cleanupResources(get, response, client);
    }
}