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:com.telefonica.iot.tidoop.apiext.http.HttpClientFactory.java

/**
 * Gets a SchemeRegistry object accepting all the X509 certificates by default.
 * @return A SchemeRegistry object./*from   ww w . j ava 2  s .  c  o  m*/
 */
private SchemeRegistry getSchemeRegistry() {
    // http://stackoverflow.com/questions/2703161/how-to-ignore-ssl-certificate-errors-in-apache-httpclient-4-0

    SSLContext sslContext = null;

    try {
        sslContext = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {
        logger.fatal("Fatal error (SSL cannot be used, no such algorithm. Details=" + e.getMessage() + ")");
        return null;
    } // try catch

    try {
        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            } // getAcceptedIssuers

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            } // getAcceptedIssuers

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            } // checkServerTrusted
        } }, new SecureRandom());
    } catch (KeyManagementException e) {
        logger.fatal("Fatal error (Cannot ignore SSL certificates. Details=" + e.getMessage() + ")");
        return null;
    } // try catch

    if (sslContext == null) {
        logger.fatal("Fatal error (Cannot ignore SSL certificates, SSL context is null)");
        return null;
    } // if

    SSLSocketFactory sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme httpsScheme = new Scheme("https", 443, sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    return schemeRegistry;
}

From source file:SandBox.testing.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    HttpParams params = new BasicHttpParams();
    HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params);
    paramsBean.setVersion(HttpVersion.HTTP_1_1);
    paramsBean.setContentCharset("UTF-8");
    paramsBean.setUseExpectContinue(false);

    params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);
    params.setParameter(CoreProtocolPNames.USER_AGENT, config.getUserAgentString());
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, config.getSocketTimeout());
    params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, config.getConnectionTimeout());

    params.setBooleanParameter("http.protocol.handle-redirects", false);

    SSLContext sslContext = null;
    try {//  w w  w .j av  a 2 s .c  om
        sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                System.out.println("getAcceptedIssuers =============");
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkClientTrusted =============");
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
                System.out.println("checkServerTrusted =============");
            }
        } }, new SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    SSLSocketFactory sf = new SSLSocketFactory(sslContext);
    Scheme httpsScheme = new Scheme("https", 443, sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);

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

    if (config.isIncludeHttpsPages()) {
        schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    }

    connectionManager = new PoolingClientConnectionManager(schemeRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    httpClient = new DefaultHttpClient(connectionManager, params);

    if (config.getProxyHost() != null) {

        if (config.getProxyUsername() != null) {
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            Header contentEncoding = entity.getContentEncoding();
            if (contentEncoding != null) {
                HeaderElement[] codecs = contentEncoding.getElements();
                for (HeaderElement codec : codecs) {
                    if (codec.getName().equalsIgnoreCase("gzip")) {
                        response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                        return;
                    }
                }
            }
        }

    });

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();

}

From source file:com.myJava.file.driver.remote.ftp.SecuredSocketFactory.java

public SecuredSocketFactory(String protocol, String protection, boolean checkServerCertificate,
        boolean implicit, InputStream certificateInputStream, String certificatePassword, FTPSClient client) {
    Logger.defaultLogger().info("Initializing secured socket factory ...");
    acceptProtocol(protocol);/*ww  w . ja  v  a 2  s .  c  o  m*/
    this.protocol = protocol;
    this.protection = protection;

    if (protection == null || (!protection.equals("C") && !protection.equals("P"))) {
        throw new IllegalArgumentException(
                "Illegal protection method : [" + protection + "]. Only \"C\" and \"P\" are accepted.");
    }

    this.implicit = implicit;
    this.client = client;

    TrustManager tm[] = null;
    KeyManager km[] = null;

    // Init the keyStore if needed
    if (certificateInputStream != null) {
        try {
            Logger.defaultLogger().info("Loading certificate ...");
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KEY_ALGORITHM);
            KeyStore ks = KeyStore.getInstance(KEY_TYPE);
            char[] pwdChars = (certificatePassword == null ? null : certificatePassword.toCharArray());
            ks.load(certificateInputStream, pwdChars);
            kmf.init(ks, pwdChars);
            km = kmf.getKeyManagers();
        } catch (Exception e) {
            Logger.defaultLogger().error(e);
        }
    }

    // Init the trustmanager if needed
    if (!checkServerCertificate) {
        Logger.defaultLogger().info("Disabling server identification ...");
        tm = NO_CHECK_TM;
    }

    try {
        sslContext = SSLContext.getInstance(protocol);
        sslContext.init(km, tm, null);
    } catch (NoSuchAlgorithmException e) {
        Logger.defaultLogger().error(e);
    } catch (KeyManagementException e) {
        Logger.defaultLogger().error(e);
    }
}

From source file:com.fine47.http.SecureSocketFactory.java

private SecureSocketFactory(String factoryId, KeyStore store, String alias) throws CertificateException,
        NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(store);

    // Loading the CA certificate from store.
    Certificate rootca = store.getCertificate(alias);

    // Turn it to X509 format.
    InputStream is = new ByteArrayInputStream(rootca.getEncoded());
    X509Certificate x509ca = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(is);
    ActivityHttpClient.silentCloseInputStream(is);

    if (null == x509ca) {
        throw new CertificateException("Found expired SSL certificate in this store: " + factoryId);
    }//from   w  ww.j a  v  a2  s. c  o  m

    // Check the CA's validity.
    x509ca.checkValidity();

    // Accepted CA is only the one installed in the store.
    acceptedIssuers = new X509Certificate[] { x509ca };

    // Get the public key.
    publicKey = rootca.getPublicKey();

    sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(null, new TrustManager[] { new X509TrustManager() {

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

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            Exception error = null;

            if (null == chain || 0 == chain.length) {
                error = new CertificateException("Certificate chain is invalid");
            } else if (null == authType || 0 == authType.length()) {
                error = new CertificateException("Authentication type is invalid");
            } else
                try {
                    for (X509Certificate cert : chain) {
                        if (ActivityHttpClient.isDebugging()) {
                            Log.d(ActivityHttpClient.LOG_TAG, "Server Certificate Details:");
                            Log.d(ActivityHttpClient.LOG_TAG, "---------------------------");
                            Log.d(ActivityHttpClient.LOG_TAG, "IssuerDN: " + cert.getIssuerDN().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "SubjectDN: " + cert.getSubjectDN().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "Serial Number: " + cert.getSerialNumber());
                            Log.d(ActivityHttpClient.LOG_TAG, "Version: " + cert.getVersion());
                            Log.d(ActivityHttpClient.LOG_TAG, "Not before: " + cert.getNotBefore().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "Not after: " + cert.getNotAfter().toString());
                            Log.d(ActivityHttpClient.LOG_TAG, "---------------------------");
                        }

                        // Make sure that it hasn't expired.
                        cert.checkValidity();

                        // Verify the certificate's chain.
                        cert.verify(publicKey);
                    }
                } catch (InvalidKeyException ex) {
                    error = ex;
                } catch (NoSuchAlgorithmException ex) {
                    error = ex;
                } catch (NoSuchProviderException ex) {
                    error = ex;
                } catch (SignatureException ex) {
                    error = ex;
                }
            if (null != error && ActivityHttpClient.isDebugging()) {
                Log.e(ActivityHttpClient.LOG_TAG, "Error while setting up a secure socket factory.", error);
                throw new CertificateException(error);
            }
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return acceptedIssuers;
        }
    } }, null);

    setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
}

From source file:com.ycj.android.common.utils.OtherUtils.java

public static void trustAllSSLForHttpsURLConnection() {
    // Create a trust manager that does not validate certificate chains
    if (trustAllCerts == null) {
        trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }/*  w  ww  .  ja  va  2  s  .  co  m*/

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

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        }};
    }
    // Install the all-trusting trust manager
    final SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    } catch (Throwable e) {
        LogUtils.e(e.getMessage(), e);
    }
    HttpsURLConnection.setDefaultHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}

From source file:com.telefonica.iot.cosmos.hive.authprovider.HttpClientFactory.java

/**
 * Gets a SSL SchemeRegistry object accepting all the X509 certificates by default.
 * @return A SSL SchemeRegistry object.//from   w w w.j a  v  a  2  s . c  o  m
 */
private SchemeRegistry getSSLSchemeRegistry() {
    // http://stackoverflow.com/questions/2703161/how-to-ignore-ssl-certificate-errors-in-apache-httpclient-4-0

    SSLContext sslContext;

    try {
        sslContext = SSLContext.getInstance("SSL");
    } catch (NoSuchAlgorithmException e) {
        LOGGER.fatal("Fatal error (SSL cannot be used, no such algorithm. Details=" + e.getMessage() + ")");
        return null;
    } // try catch // try catch

    try {
        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            } // getAcceptedIssuers

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            } // getAcceptedIssuers

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            } // checkServerTrusted
        } }, new SecureRandom());
    } catch (KeyManagementException e) {
        LOGGER.fatal("Fatal error (Cannot ignore SSL certificates. Details=" + e.getMessage() + ")");
        return null;
    } // try catch // try catch

    if (sslContext == null) {
        LOGGER.fatal("Fatal error (Cannot ignore SSL certificates, SSL context is null)");
        return null;
    } // if

    SSLSocketFactory sf = new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme httpsScheme = new Scheme("https", 443, sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);
    return schemeRegistry;
}

From source file:io.getlime.push.configuration.PowerAuthWebServiceConfiguration.java

/**
 * Prepare a correctly configured PowerAuthServiceClient instance with the service
 * URL specified using 'powerauth.service.url' server property.
 *
 * @param marshaller JAXB marshaller//www.  j  a  v a 2  s .  com
 * @return Correctly configured PowerAuthServiceClient instance with the service
 * URL specified using 'powerauth.service.url' server property
 */
@Bean
public PowerAuthServiceClient powerAuthClient(Jaxb2Marshaller marshaller) {
    PowerAuthServiceClient client = new PowerAuthServiceClient();
    client.setDefaultUri(powerAuthServiceUrl);
    client.setMarshaller(marshaller);
    client.setUnmarshaller(marshaller);

    // if invalid SSL certificates should be accepted
    if (acceptInvalidSslCertificate) {

        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        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) {
            }

        } };

        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            // ... ignore
        }

    }

    // if there is a configuration with security credentials, add interceptor
    if (!clientToken.isEmpty()) {
        ClientInterceptor[] interceptors = new ClientInterceptor[] { securityInterceptor() };
        client.setInterceptors(interceptors);
    }
    return client;
}

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

static public Scheme createDoNotVerifyHttpsScheme() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager sslTrustManager = new DoNotVerifySSLCertificateTrustManager();
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { sslTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return new Scheme("https", sf, 443);
}

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;
        }// w  w w  . j av a2s.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:cn.com.infohold.p2papp.common.gate.OtherUtils.java

public static void trustAllSSLForHttpsURLConnection() {
    // Create a trust manager that does not validate certificate chains
    if (trustAllCerts == null) {
        trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }//from  w w  w.j  ava 2  s . co  m

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

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
    }
    // Install the all-trusting trust manager
    final SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    } catch (Throwable e) {
        LogUtils.e(e.getMessage(), e);
    }
    HttpsURLConnection
            .setDefaultHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}