List of usage examples for javax.net.ssl X509TrustManager X509TrustManager
X509TrustManager
From source file:com.irccloud.android.NetworkConnection.java
@SuppressWarnings("deprecation") public NetworkConnection() { String version;//from w w w. j a v a 2 s .c o m String network_type = null; try { version = "/" + IRCCloudApplication.getInstance().getPackageManager().getPackageInfo( IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), 0).versionName; } catch (Exception e) { version = ""; } try { ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance() .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni != null) network_type = ni.getTypeName(); } catch (Exception e) { } try { config = new JSONObject(PreferenceManager .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()) .getString("config", "{}")); } catch (JSONException e) { e.printStackTrace(); config = new JSONObject(); } useragent = "IRCCloud" + version + " (" + android.os.Build.MODEL + "; " + Locale.getDefault().getCountry().toLowerCase() + "; " + "Android " + android.os.Build.VERSION.RELEASE; WindowManager wm = (WindowManager) IRCCloudApplication.getInstance() .getSystemService(Context.WINDOW_SERVICE); useragent += "; " + wm.getDefaultDisplay().getWidth() + "x" + wm.getDefaultDisplay().getHeight(); if (network_type != null) useragent += "; " + network_type; useragent += ")"; WifiManager wfm = (WifiManager) IRCCloudApplication.getInstance().getApplicationContext() .getSystemService(Context.WIFI_SERVICE); wifiLock = wfm.createWifiLock(TAG); kms = new X509ExtendedKeyManager[1]; kms[0] = new X509ExtendedKeyManager() { @Override public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) { return SSLAuthAlias; } @Override public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { throw new UnsupportedOperationException(); } @Override public X509Certificate[] getCertificateChain(String alias) { return SSLAuthCertificateChain; } @Override public String[] getClientAliases(String keyType, Principal[] issuers) { throw new UnsupportedOperationException(); } @Override public String[] getServerAliases(String keyType, Principal[] issuers) { throw new UnsupportedOperationException(); } @Override public PrivateKey getPrivateKey(String alias) { return SSLAuthKey; } }; tms = new TrustManager[1]; tms[0] = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { throw new CertificateException("Not implemented"); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { try { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509"); trustManagerFactory.init((KeyStore) null); for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { X509TrustManager x509TrustManager = (X509TrustManager) trustManager; x509TrustManager.checkServerTrusted(chain, authType); } } } catch (KeyStoreException e) { throw new CertificateException(e); } catch (NoSuchAlgorithmException e) { throw new CertificateException(e); } if (BuildConfig.SSL_FPS != null && BuildConfig.SSL_FPS.length > 0) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] sha1 = md.digest(chain[0].getEncoded()); // http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java final char[] hexArray = "0123456789ABCDEF".toCharArray(); char[] hexChars = new char[sha1.length * 2]; for (int j = 0; j < sha1.length; j++) { int v = sha1[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } String hexCharsStr = new String(hexChars); boolean matched = false; for (String fp : BuildConfig.SSL_FPS) { if (fp.equals(hexCharsStr)) { matched = true; break; } } if (!matched) throw new CertificateException("Incorrect CN in cert chain"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } } @Override public X509Certificate[] getAcceptedIssuers() { return null; } }; WebSocketClient.setTrustManagers(tms); }
From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java
private SSLSocketFactory generateSSLContextFromPEMCertString(String pemCert) { if (StringUtils.isNotBlank(pemCert) && pemCert.startsWith(BEGIN_CERT)) { try {/* w w w. ja v a2 s . c o m*/ InputStream certInputStream = IOUtils.toInputStream(pemCert); final X509Certificate trustedCert = (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(certInputStream); final TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws CertificateException { if (!certs[0].equals(trustedCert)) { throw new CertificateException(); } } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws CertificateException { if (!certs[0].equals(trustedCert)) { throw new CertificateException(); } } } }; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustManager, new java.security.SecureRandom()); return sslContext.getSocketFactory(); } catch (NoSuchAlgorithmException e) { logger.error("A NoSuchAlgorithmException occurred: ", e); } catch (KeyManagementException e) { logger.error("A KeyManagementException occurred: ", e); } catch (CertificateException e) { logger.error("A CertificateException occurred: ", e); } } else { logger.error("Cert is empty"); } return null; }
From source file:org.eclipse.lyo.client.oslc.OslcClient.java
private void setupSSLSupport(TrustManager[] trustManagers, X509HostnameVerifier hostnameVerifier) { ClientConnectionManager connManager = httpClient.getConnectionManager(); SchemeRegistry schemeRegistry = connManager.getSchemeRegistry(); schemeRegistry.unregister("https"); /** Create a trust manager that does not validate certificate chains */ TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { /** Ignore Method Call */ }//from ww w . ja v a 2s. co m public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) { /** Ignore Method Call */ } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } } }; try { SSLContext sc = findInstalledSecurityContext(); if (trustManagers == null) { trustManagers = trustAllCerts; } if (hostnameVerifier == null) { hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; } sc.init(null, trustManagers, new java.security.SecureRandom()); SSLSocketFactory sf = new SSLSocketFactory(sc, hostnameVerifier); Scheme https = new Scheme("https", 443, sf); //$NON-NLS-1$ schemeRegistry.register(https); } catch (NoSuchAlgorithmException e) { /* Fail Silently */ } catch (KeyManagementException e) { /* Fail Silently */ } }
From source file:org.apache.geode.management.internal.cli.commands.ConnectCommand.java
private TrustManager[] getTrustManagers(SSLConfig sslConfig, boolean skipSslVerification) throws Exception { FileInputStream trustStoreStream = null; TrustManagerFactory trustManagerFactory = null; if (skipSslVerification) { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }/*from w w w .ja v a2s .c om*/ public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; return trustAllCerts; } try { // load server public key if (StringUtils.isNotBlank(sslConfig.getTruststore())) { KeyStore serverPub = KeyStore.getInstance(sslConfig.getTruststoreType()); trustStoreStream = new FileInputStream(sslConfig.getTruststore()); serverPub.load(trustStoreStream, sslConfig.getTruststorePassword().toCharArray()); trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(serverPub); } } finally { if (trustStoreStream != null) { trustStoreStream.close(); } } return trustManagerFactory != null ? trustManagerFactory.getTrustManagers() : null; }
From source file:de.unidue.stud.sehawagn.oidcclient.SimpleOIDCClient.java
private static SSLContext getTrustEverybodySSLContext() { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; }//from w w w. j av a 2s. c o m public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext sc = null; try { sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } return sc; }
From source file:com.wso2.mobile.mdm.utils.ServerUtilities.java
private static void trustAllHosts() { X509TrustManager easyTrustManager = new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return new java.security.cert.X509Certificate[] {}; }//from w w w. j av a 2s . c om @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { // TODO Auto-generated method stub } }; // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { easyTrustManager }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.accada.epcis.repository.query.QuerySubscription.java
/** * Retrieves an "all-trusting" HTTP URL connection object, by disabling the * validation of certificates and overriding the default trust manager with * one that trusts all certificates./* w w w . j a v a 2s. c om*/ * * @param url * The URL on which a connection will be opened. * @return A HttpURLConnection connection object. * @throws IOException * If an I/O error occurred. */ private HttpURLConnection getAllTrustingConnection(URL url) throws IOException { // 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 try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { LOG.error("Unable to install the all-trusting trust manager", e); } return getConnection(url); }
From source file:net.java.sip.communicator.impl.certificate.CertificateServiceImpl.java
public X509TrustManager getTrustManager(final Iterable<String> identitiesToTest, final CertificateMatcher clientVerifier, final CertificateMatcher serverVerifier) throws GeneralSecurityException { // obtain the default X509 trust manager X509TrustManager defaultTm = null; TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); //workaround for https://bugs.openjdk.java.net/browse/JDK-6672015 KeyStore ks = null;/*ww w . ja v a2 s.c o m*/ String tsType = System.getProperty("javax.net.ssl.trustStoreType", null); if ("Windows-ROOT".equals(tsType)) { try { ks = KeyStore.getInstance(tsType); ks.load(null, null); int numEntries = keyStoreAppendIndex(ks); logger.info( "Using Windows-ROOT. Aliases sucessfully renamed on " + numEntries + " root certificates."); } catch (Exception e) { logger.error("Could not rename Windows-ROOT aliases", e); } } tmFactory.init(ks); for (TrustManager m : tmFactory.getTrustManagers()) { if (m instanceof X509TrustManager) { defaultTm = (X509TrustManager) m; break; } } if (defaultTm == null) throw new GeneralSecurityException("No default X509 trust manager found"); final X509TrustManager tm = defaultTm; return new X509TrustManager() { private boolean serverCheck; public X509Certificate[] getAcceptedIssuers() { return tm.getAcceptedIssuers(); } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { serverCheck = true; checkCertTrusted(chain, authType); } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { serverCheck = false; checkCertTrusted(chain, authType); } private void checkCertTrusted(X509Certificate[] chain, String authType) throws CertificateException { // check and default configurations for property // if missing default is null - false String defaultAlwaysTrustMode = CertificateVerificationActivator.getResources() .getSettingsString(CertificateService.PNAME_ALWAYS_TRUST); if (config.getBoolean(PNAME_ALWAYS_TRUST, Boolean.parseBoolean(defaultAlwaysTrustMode))) return; try { // check the certificate itself (issuer, validity) try { chain = tryBuildChain(chain); } catch (Exception e) { } // don't care and take the chain as is if (serverCheck) tm.checkServerTrusted(chain, authType); else tm.checkClientTrusted(chain, authType); if (identitiesToTest == null || !identitiesToTest.iterator().hasNext()) return; else if (serverCheck) serverVerifier.verify(identitiesToTest, chain[0]); else clientVerifier.verify(identitiesToTest, chain[0]); // ok, globally valid cert } catch (CertificateException e) { String thumbprint = getThumbprint(chain[0], THUMBPRINT_HASH_ALGORITHM); String message = null; List<String> propNames = new LinkedList<String>(); List<String> storedCerts = new LinkedList<String>(); String appName = R.getSettingsString("service.gui.APPLICATION_NAME"); if (identitiesToTest == null || !identitiesToTest.iterator().hasNext()) { String propName = PNAME_CERT_TRUST_PREFIX + ".server." + thumbprint; propNames.add(propName); message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT_NOHOST", new String[] { appName }); // get the thumbprints from the permanent allowances String hashes = config.getString(propName); if (hashes != null) for (String h : hashes.split(",")) storedCerts.add(h); // get the thumbprints from the session allowances List<String> sessionCerts = sessionAllowedCertificates.get(propName); if (sessionCerts != null) storedCerts.addAll(sessionCerts); } else { if (serverCheck) { message = R.getI18NString("service.gui." + "CERT_DIALOG_DESCRIPTION_TXT", new String[] { appName, identitiesToTest.toString() }); } else { message = R.getI18NString("service.gui." + "CERT_DIALOG_PEER_DESCRIPTION_TXT", new String[] { appName, identitiesToTest.toString() }); } for (String identity : identitiesToTest) { String propName = PNAME_CERT_TRUST_PREFIX + ".param." + identity; propNames.add(propName); // get the thumbprints from the permanent allowances String hashes = config.getString(propName); if (hashes != null) for (String h : hashes.split(",")) storedCerts.add(h); // get the thumbprints from the session allowances List<String> sessionCerts = sessionAllowedCertificates.get(propName); if (sessionCerts != null) storedCerts.addAll(sessionCerts); } } if (!storedCerts.contains(thumbprint)) { switch (verify(chain, message)) { case DO_NOT_TRUST: logger.info("Untrusted certificate", e); throw new CertificateException("The peer provided certificate with Subject <" + chain[0].getSubjectDN() + "> is not trusted", e); case TRUST_ALWAYS: for (String propName : propNames) { String current = config.getString(propName); String newValue = thumbprint; if (current != null) newValue += "," + current; config.setProperty(propName, newValue); } break; case TRUST_THIS_SESSION_ONLY: for (String propName : propNames) getSessionCertEntry(propName).add(thumbprint); break; } } // ok, we've seen this certificate before } } private X509Certificate[] tryBuildChain(X509Certificate[] chain) throws IOException, URISyntaxException, CertificateException { // Only try to build chains for servers that send only their // own cert, but no issuer. This also matches self signed (will // be ignored later) and Root-CA signed certs. In this case we // throw the Root-CA away after the lookup if (chain.length != 1) return chain; // ignore self signed certs if (chain[0].getIssuerDN().equals(chain[0].getSubjectDN())) return chain; // prepare for the newly created chain List<X509Certificate> newChain = new ArrayList<X509Certificate>(chain.length + 4); for (X509Certificate cert : chain) { newChain.add(cert); } // search from the topmost certificate upwards CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); X509Certificate current = chain[chain.length - 1]; boolean foundParent; int chainLookupCount = 0; do { foundParent = false; // extract the url(s) where the parent certificate can be // found byte[] aiaBytes = current.getExtensionValue(Extension.authorityInfoAccess.getId()); if (aiaBytes == null) break; AuthorityInformationAccess aia = AuthorityInformationAccess .getInstance(X509ExtensionUtil.fromExtensionValue(aiaBytes)); // the AIA may contain different URLs and types, try all // of them for (AccessDescription ad : aia.getAccessDescriptions()) { // we are only interested in the issuer certificate, // not in OCSP urls the like if (!ad.getAccessMethod().equals(AccessDescription.id_ad_caIssuers)) continue; GeneralName gn = ad.getAccessLocation(); if (!(gn.getTagNo() == GeneralName.uniformResourceIdentifier && gn.getName() instanceof DERIA5String)) continue; URI uri = new URI(((DERIA5String) gn.getName()).getString()); // only http(s) urls; LDAP is taken care of in the // default implementation if (!(uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equals("https"))) continue; X509Certificate cert = null; // try to get cert from cache first to avoid consecutive // (slow) http lookups AiaCacheEntry cache = aiaCache.get(uri); if (cache != null && cache.cacheDate.after(new Date())) { cert = cache.cert; } else { // download if no cache entry or if it is expired if (logger.isDebugEnabled()) logger.debug("Downloading parent certificate for <" + current.getSubjectDN() + "> from <" + uri + ">"); try { InputStream is = HttpUtils.openURLConnection(uri.toString()).getContent(); cert = (X509Certificate) certFactory.generateCertificate(is); } catch (Exception e) { logger.debug("Could not download from <" + uri + ">"); } // cache for 10mins aiaCache.put(uri, new AiaCacheEntry(new Date(new Date().getTime() + 10 * 60 * 1000), cert)); } if (cert != null) { if (!cert.getIssuerDN().equals(cert.getSubjectDN())) { newChain.add(cert); foundParent = true; current = cert; break; // an AD was valid, ignore others } else logger.debug("Parent is self-signed, ignoring"); } } chainLookupCount++; } while (foundParent && chainLookupCount < 10); chain = newChain.toArray(chain); return chain; } }; }
From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java
/** * SSL?TrustManager???SSL?/* ww w . ja v a 2s . c o m*/ * HttpsURLConnection???? */ private void trustAllHosts() { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } }; // all-trusting TrustManager try { // ?SSL mDefaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory(); // TrustManager SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { XLog.e(CLASS_NAME, e.getMessage()); } }
From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java
private SSLSocketFactory generateSSLContextWhichAcceptAllSSLCertificats() { Security.addProvider(Security.getProvider("SunJCE")); TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override/*from w w w .ja va 2 s . co m*/ public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { } } }; try { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new SecureRandom()); return sslContext.getSocketFactory(); } catch (KeyManagementException e) { logger.error("A KeyManagementException occurred", e); } catch (NoSuchAlgorithmException e) { logger.error("A NoSuchAlgorithmException occurred", e); } return null; }