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

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

Introduction

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

Prototype

X509HostnameVerifier STRICT_HOSTNAME_VERIFIER

To view the source code for org.apache.http.conn.ssl SSLSocketFactory STRICT_HOSTNAME_VERIFIER.

Click Source Link

Usage

From source file:net.openwatch.acluaz.http.AZHttpClient.java

private SSLSocketFactory newSslSocketFactory() {
    try {//  ww  w . ja v a 2s  .  co 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.azkeystore);
        try {
            // Initialize the keystore with the provided trusted certificates
            // Also provide the password of the keystore
            trusted.load(in, SECRETS.SSL_KEYSTORE_PASS.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.zywx.wbpalmstar.platform.certificates.Http.java

public static HttpsURLConnection getHttpsURLConnection(URL url) throws Exception {
    HttpsURLConnection mConnection = null;
    mConnection = (HttpsURLConnection) url.openConnection();
    javax.net.ssl.SSLSocketFactory ssFact = null;
    ssFact = Http.getSSLSocketFactory();
    ((HttpsURLConnection) mConnection).setSSLSocketFactory(ssFact);
    if (!isCheckTrustCert()) {
        ((HttpsURLConnection) mConnection).setHostnameVerifier(new HX509HostnameVerifier());
    } else {//  w  w w .  ja  v  a 2s .  co  m
        ((HttpsURLConnection) mConnection).setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
    }
    return mConnection;
}

From source file:com.gallery.GalleryRemote.GalleryComm.java

protected GalleryComm(Gallery g, StatusUpdate su) {
    if (g == null) {
        throw new IllegalArgumentException("Must supply a non-null gallery.");
    }/*from  w  w  w.j a va  2s.c om*/

    this.g = g;
    this.su = su;

    SingleClientConnManager cm = null;

    // Set all-trusting SSL manager, if necessary
    if (g.getUrl().getProtocol().equals("https")) {
        try {
            SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getInstance("TLS"),
                    SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("https", sf, 443));
            cm = new SingleClientConnManager(schemeRegistry);
        } catch (NoSuchAlgorithmException e) {
            Log.logException(Log.LEVEL_CRITICAL, MODULE, e);
        }
    }

    httpclient = new DefaultHttpClient(cm);

    // Use default proxy (as defined by the JVM)
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpclient.setRoutePlanner(routePlanner);

    // use GR User-Agent
    httpclient.removeRequestInterceptorByClass(RequestUserAgent.class);
    final String ua = g.getUserAgent();
    httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            request.setHeader(HTTP.USER_AGENT, ua);
        }
    });
}

From source file:com.swisscom.safeconnect.backend.PlumberTask.java

public static HttpClient getNewHttpClient(Context context, HttpParams params) {
    InputStream is = null;//from  w ww .  j a v a  2s  .c om
    try {
        synchronized (mKeystoreLock) {
            if (keyStore == null) {
                is = context.getAssets().open("swisscom.bks");
                keyStore = KeyStore.getInstance("BKS");
                keyStore.load(is, "sw1ssc0m".toCharArray());
            }

            if (sslSocketFactory == null) {
                sslSocketFactory = new SwisscomSslSocketFactory(keyStore);
                sslSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            }

            if (schemeRegistry == null) {
                schemeRegistry = new SchemeRegistry();
                schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
                schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
            }

            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "UTF-8");
        }

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, schemeRegistry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        if (BuildConfig.DEBUG)
            Log.e(Config.TAG, "error", e);
        return new DefaultHttpClient();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                if (BuildConfig.DEBUG)
                    Log.e(Config.TAG, "error", e);
            }
        }
    }
}

From source file:com.emc.vipr.services.s3.ViPRS3HttpClient.java

public ViPRS3HttpClient(ViPRS3Config viprConfig) {
    super(viprConfig.getClientConfiguration(), new SmartHttpClient(viprConfig.toSmartClientConfig()), null);

    ClientConfiguration azConfig = viprConfig.getClientConfiguration();
    HttpParams httpClientParams = httpClient.getParams();

    HttpConnectionParams.setConnectionTimeout(httpClientParams, azConfig.getConnectionTimeout());
    HttpConnectionParams.setSoTimeout(httpClientParams, azConfig.getSocketTimeout());
    HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, true);
    HttpConnectionParams.setTcpNoDelay(httpClientParams, true);

    int socketSendBufferSizeHint = azConfig.getSocketBufferSizeHints()[0];
    int socketReceiveBufferSizeHint = azConfig.getSocketBufferSizeHints()[1];
    if (socketSendBufferSizeHint > 0 || socketReceiveBufferSizeHint > 0) {
        HttpConnectionParams.setSocketBufferSize(httpClientParams,
                Math.max(socketSendBufferSizeHint, socketReceiveBufferSizeHint));
    }/* ww w .  ja  v a  2s  . c  om*/

    ClientConnectionManager connectionManager = httpClient.getConnectionManager();
    ((SmartHttpClient) httpClient).setRedirectStrategy(new LocationHeaderNotRequiredRedirectStrategy());

    try {
        Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
        SSLSocketFactory sf = new SSLSocketFactory(SSLContext.getDefault(),
                SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        Scheme https = new Scheme("https", 443, sf);
        SchemeRegistry sr = connectionManager.getSchemeRegistry();
        sr.register(http);
        sr.register(https);
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException("Unable to access default SSL context", e);
    }

    /*
     * If SSL cert checking for endpoints has been explicitly disabled,
     * register a new scheme for HTTPS that won't cause self-signed certs to
     * error out.
     */
    if (System.getProperty(SDKGlobalConfiguration.DISABLE_CERT_CHECKING_SYSTEM_PROPERTY) != null) {
        Scheme sch = new Scheme("https", 443, new TrustingSocketFactory());
        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    }

    /* Set proxy if configured */
    String proxyHost = azConfig.getProxyHost();
    int proxyPort = azConfig.getProxyPort();
    if (proxyHost != null && proxyPort > 0) {
        log.info("Configuring Proxy. Proxy Host: " + proxyHost + " " + "Proxy Port: " + proxyPort);
        HttpHost proxyHttpHost = new HttpHost(proxyHost, proxyPort);
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHttpHost);

        String proxyUsername = azConfig.getProxyUsername();
        String proxyPassword = azConfig.getProxyPassword();
        String proxyDomain = azConfig.getProxyDomain();
        String proxyWorkstation = azConfig.getProxyWorkstation();

        if (proxyUsername != null && proxyPassword != null) {
            ((SmartHttpClient) httpClient).getCredentialsProvider().setCredentials(
                    new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }

        // Add a request interceptor that sets up proxy authentication pre-emptively if configured
        if (azConfig.isPreemptiveBasicProxyAuth()) {
            ((SmartHttpClient) httpClient).addRequestInterceptor(new PreemptiveProxyAuth(proxyHttpHost), 0);
        }
    }
}

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

@Override
protected void onHandleIntent(Intent intent) {
    if (intent.getAction().equals(stopAction)) {
        stopSelf();// w  w w  .  j a v a 2s . 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:groovyx.net.http.AuthConfig.java

/**
 * Sets a certificate to be used for SSL authentication.  See
 * {@link Class#getResource(String)} for how to get a URL from a resource
 * on the classpath.//from  w  w  w .  j a  va  2  s .  co m
 * @param certURL URL to a JKS keystore where the certificate is stored.
 * @param password password to decrypt the keystore
 */
public void certificate(String certURL, String password) throws GeneralSecurityException, IOException {

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream jksStream = new URL(certURL).openStream();
    try {
        keyStore.load(jksStream, password.toCharArray());
    } finally {
        jksStream.close();
    }

    SSLSocketFactory ssl = new SSLSocketFactory(keyStore, password);
    ssl.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);

    builder.getClient().getConnectionManager().getSchemeRegistry().register(new Scheme("https", ssl, 443));
}

From source file:com.ntsync.android.sync.client.MyHttpClient.java

private SocketFactory getSSLSocketFactory() {
    InputStream in = null;//from   www  . ja v a  2 s .  c om
    SocketFactory socketFack = null;
    try {
        KeyStore trusted = KeyStore.getInstance("BKS");
        in = context.getResources().openRawResource(R.raw.mykeystore);
        trusted.load(in, "pwd23key".toCharArray());
        SSLSocketFactory sslSocketFack = new SSLSocketFactory(trusted);
        socketFack = sslSocketFack;
        if (Constants.USE_RELEASE_CONFIG) {
            sslSocketFack.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        } else {
            Log.w(TAG, "Disable SSL Hostname verification");
            sslSocketFack.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        }
    } catch (GeneralSecurityException e) {
        Log.e(TAG, "Loading truststore failed.", e);
    } catch (IOException e) {
        Log.e(TAG, "Loading truststore failed.", e);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            Log.e(TAG, "closing filescocket failed.", e);
        }
    }
    if (socketFack == null) {
        Log.w(TAG, "Fallback to custom ssl socket factory.");
        socketFack = new MySSLSocketFactory();
    }
    return socketFack;
}