List of usage examples for javax.net.ssl X509TrustManager X509TrustManager
X509TrustManager
From source file:org.musicmount.io.server.dav.DAVResourceProvider.java
protected Sardine createSardine(final ServerFileSystem fileSystem) { /*/*from w ww .j a v a 2 s. c om*/ * extract user/password */ String user = null; String password = null; if (fileSystem.getUserInfo() != null) { String[] userAndPassword = fileSystem.getUserInfo().split(":"); user = userAndPassword[0]; password = userAndPassword.length > 1 ? userAndPassword[1] : null; } /* * create customized sardine */ return new SardineImpl(user, password, null) { @Override protected Registry<ConnectionSocketFactory> createDefaultSchemeRegistry() { ConnectionSocketFactory socketFactory; if ("https".equalsIgnoreCase(fileSystem.getScheme())) { socketFactory = createDefaultSecureSocketFactory(); } else { socketFactory = createDefaultSocketFactory(); } return RegistryBuilder.<ConnectionSocketFactory>create() .register(fileSystem.getScheme(), socketFactory).build(); } @Override protected ConnectionSocketFactory createDefaultSecureSocketFactory() { try { // trust anybody... SSLContext context = SSLContext.getInstance("TLS"); X509TrustManager trustManager = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; context.init(null, new TrustManager[] { trustManager }, null); return new SSLConnectionSocketFactory(context, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (NoSuchAlgorithmException | KeyManagementException e) { // should not happen... } return super.createDefaultSecureSocketFactory(); } @Override protected <T> T execute(HttpRequestBase request, ResponseHandler<T> responseHandler) throws IOException { /* * Sardine re-executes a PUT request after a org.apache.http.NoHttpResponseException without resetting it... */ if (request.isAborted()) { request.reset(); } return super.execute(request, responseHandler); } @Override public ContentLengthInputStream get(String url, Map<String, String> headers) throws IOException { /* * abort rather than consume entity for better performance */ final HttpGet get = new HttpGet(url); for (String header : headers.keySet()) { get.addHeader(header, headers.get(header)); } // Must use #execute without handler, otherwise the entity is consumed already after the handler exits. final HttpResponse response = this.execute(get); VoidResponseHandler handler = new VoidResponseHandler(); try { handler.handleResponse(response); // Will consume or abort the entity when the stream is closed. PositionInputStream positionInputStream = new PositionInputStream( response.getEntity().getContent()) { public void close() throws IOException { if (getPosition() == response.getEntity().getContentLength()) { EntityUtils.consume(response.getEntity()); } else { // partial read or unknown content length get.abort(); } } }; return new ContentLengthInputStream(positionInputStream, response.getEntity().getContentLength()); } catch (IOException ex) { get.abort(); throw ex; } } }; }
From source file:com.fujitsu.dc.client.http.HttpClientFactory.java
/** * This method is used to generate SSLSocket. * @return SSLSocket that is generated// w w w .jav a 2 s . c o m */ private static SSLSocketFactory createInsecureSSLSocketFactory() { SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("SSL"); } catch (NoSuchAlgorithmException e1) { throw new RuntimeException(e1); } try { sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { // System.out.println("getAcceptedIssuers ============="); X509Certificate[] ret = new X509Certificate[0]; return ret; } public final void checkClientTrusted(final X509Certificate[] certs, final String authType) { // System.out.println("checkClientTrusted ============="); } public final void checkServerTrusted(final X509Certificate[] certs, final String authType) { // System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); } catch (KeyManagementException e1) { throw new RuntimeException(e1); } HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier); // socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); return socketFactory; }
From source file:io.personium.client.http.HttpClientFactory.java
/** * This method is used to generate SSLSocket. * @return SSLSocket that is generated/*from w ww . j a v a 2s . c om*/ */ private static SSLSocketFactory createInsecureSSLSocketFactory() { SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("TLSv1.2"); } catch (NoSuchAlgorithmException e1) { throw new RuntimeException(e1); } try { sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { // System.out.println("getAcceptedIssuers ============="); X509Certificate[] ret = new X509Certificate[0]; return ret; } public final void checkClientTrusted(final X509Certificate[] certs, final String authType) { // System.out.println("checkClientTrusted ============="); } public final void checkServerTrusted(final X509Certificate[] certs, final String authType) { // System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); } catch (KeyManagementException e1) { throw new RuntimeException(e1); } HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier); // socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); return socketFactory; }
From source file:com.linkedin.pinot.common.utils.ClientSSLContextGenerator.java
private TrustManager[] setupTrustManagers() throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException { // This is the cert authority that validates server's cert, so we need to put it in our // trustStore. if (_serverCACertFile != null) { LOGGER.info("Initializing trust store from {}", _serverCACertFile); FileInputStream is = new FileInputStream(new File(_serverCACertFile)); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null);//from w w w .j a v a2 s . com CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE); int i = 0; while (is.available() > 0) { X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is); LOGGER.info("Read certificate serial number {} by issuer {} ", cert.getSerialNumber().toString(16), cert.getIssuerDN().toString()); String serverKey = "https-server-" + i; trustStore.setCertificateEntry(serverKey, cert); i++; } TrustManagerFactory tmf = TrustManagerFactory.getInstance(CERTIFICATE_TYPE); tmf.init(trustStore); LOGGER.info("Successfully initialized trust store"); return tmf.getTrustManagers(); } // Server verification disabled. Trust all servers TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }; return trustAllCerts; }
From source file:com.gmobi.poponews.util.HttpHelper.java
static void disableSslCheck() { if (initialized) return;/*from w w w.j a v a 2s. co m*/ TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; 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() { public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); initialized = true; } catch (Exception e) { Logger.error(e); } }
From source file:com.sitewhere.groovy.device.communication.rest.RestHelper.java
/** * Create SSL context that allows bad certificates. * //from w ww . ja v a 2 s. c om * @return */ protected SSLContext createContext() { 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, null); SSLContext.setDefault(sc); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); return sc; } catch (Exception e) { } return null; }
From source file:org.openadaptor.util.PropertiesPoster.java
/** * Utility method which will attempt to POST the supplied properties information to the supplied URL. * /*from w ww . ja va 2 s . c o m*/ * This method currently contains an all trusting trust manager for use with https. This will be replaced with a more * secure trust manager which will use a cert store. * * @param registrationURL * @param properties * @throws Exception */ protected static void syncPostHttp(String registrationURL, Properties properties) throws Exception { URL url = new URL(registrationURL); String postData = generatePOSTData(properties); log.debug("Protocol: " + url.getProtocol()); if (url.getProtocol().equals("https")) { // https connection // TODO: Replace this all trusting manager with one that uses a cert store // 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 the all-trusting trust manager SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection secureConnection = null; HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); secureConnection = (HttpsURLConnection) url.openConnection(); secureConnection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(secureConnection.getOutputStream()); writer.write(postData); writer.flush(); int responseCode = secureConnection.getResponseCode(); if (HttpsURLConnection.HTTP_OK != responseCode) { log.error("\nFailed to register. Response Code " + responseCode + "\nResponse message:" + secureConnection.getResponseMessage() + "\nRegistration URL: " + registrationURL + "\nData: " + generateString(properties)); } BufferedReader br = new BufferedReader(new InputStreamReader(secureConnection.getInputStream())); String line; while ((line = br.readLine()) != null) { log.debug("Returned data: " + line); } writer.close(); br.close(); } else { // Normal http connection HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(postData); writer.flush(); int responseCode = connection.getResponseCode(); if (HttpURLConnection.HTTP_OK != responseCode) { log.error("\nFailed to register. Response Code " + responseCode + "\nResponse message:" + connection.getResponseMessage() + "\nRegistration URL: " + registrationURL + "\nData: " + generateString(properties)); } BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = br.readLine()) != null) { log.debug("Returned data: " + line); } writer.close(); br.close(); } }
From source file:org.kontalk.client.KontalkConnection.java
@SuppressLint("AllowAllHostnameVerifier") private static void setupSSL(XMPPTCPConnectionConfiguration.Builder builder, boolean direct, PrivateKey privateKey, X509Certificate bridgeCert, boolean acceptAnyCertificate, KeyStore trustStore) { try {/*from w w w . ja v a 2 s .co m*/ SSLContext ctx = SSLContext.getInstance("TLS"); KeyManager[] km = null; if (privateKey != null && bridgeCert != null) { // in-memory keystore KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, null); keystore.setKeyEntry("private", privateKey, null, new Certificate[] { bridgeCert }); // key managers KeyManagerFactory kmFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmFactory.init(keystore, null); km = kmFactory.getKeyManagers(); // disable PLAIN mechanism if not upgrading from legacy if (!LegacyAuthentication.isUpgrading()) { // blacklist PLAIN mechanism SASLAuthentication.blacklistSASLMechanism("PLAIN"); } } // trust managers TrustManager[] tm; if (acceptAnyCertificate) { tm = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @SuppressLint("TrustAllX509TrustManager") @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @SuppressLint("TrustAllX509TrustManager") @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } }; builder.setHostnameVerifier(new AllowAllHostnameVerifier()); } else { // builtin keystore TrustManagerFactory tmFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmFactory.init(trustStore); tm = tmFactory.getTrustManagers(); } ctx.init(km, tm, null); builder.setCustomSSLContext(ctx); if (direct) builder.setSocketFactory(ctx.getSocketFactory()); // SASL EXTERNAL is already enabled in Smack } catch (Exception e) { Log.w(TAG, "unable to setup SSL connection", e); } }
From source file:org.apache.syncope.core.util.ConnIdBundleManager.java
private static void initRemote(final URI location) { // 1. Extract conf params for remote connection from given URI final String host = location.getHost(); final int port = location.getPort(); final GuardedString key = new GuardedString(location.getUserInfo().toCharArray()); final boolean useSSL = location.getScheme().equals("connids"); final List<TrustManager> trustManagers = new ArrayList<TrustManager>(); final String[] params = StringUtils.isBlank(location.getQuery()) ? null : location.getQuery().split("&"); if (params != null && params.length > 0) { final String[] trustAllCerts = params[0].split("="); if (trustAllCerts != null && trustAllCerts.length > 1 && "trustAllCerts".equalsIgnoreCase(trustAllCerts[0]) && "true".equalsIgnoreCase(trustAllCerts[1])) { trustManagers.add(new X509TrustManager() { @Override//w w w . j a va2 s .co m public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { // no checks, trust all } @Override public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { // no checks, trust all } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }); } } LOG.debug( "Configuring remote connector server:" + "\n\tHost: {}" + "\n\tPort: {}" + "\n\tKey: {}" + "\n\tUseSSL: {}" + "\n\tTrustAllCerts: {}", host, port, key, useSSL, !trustManagers.isEmpty()); RemoteFrameworkConnectionInfo info = new RemoteFrameworkConnectionInfo(host, port, key, useSSL, trustManagers, 60 * 1000); LOG.debug("Remote connection info: {}", info); // 2. Get connector info manager ConnectorInfoManager manager = ConnectorInfoManagerFactory.getInstance().getRemoteManager(info); if (manager == null) { throw new NotFoundException("Remote ConnectorInfoManager"); } CONN_MANAGERS.put(location, manager); }
From source file:com.phonegap.FileTransfer.java
/** * This function will install a trust manager that will blindly trust all SSL * certificates. The reason this code is being added is to enable developers * to do development using self signed SSL certificates on their web server. * //w w w. j a va 2 s.co m * The standard HttpsURLConnection class will throw an exception on self * signed certificates if this code is not run. */ private void trustAllHosts() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = 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 { } } }; // Install the all-trusting trust manager try { // Backup the current SSL socket factory defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); // Install our all trusting manager SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { Log.e(LOG_TAG, e.getMessage(), e); } }