List of usage examples for javax.net.ssl TrustManagerFactory getDefaultAlgorithm
public static final String getDefaultAlgorithm()
From source file:org.apache.cassandra.hadoop.cql3.CqlConfigHelper.java
private static SSLContext getSSLContext(String truststorePath, String truststorePassword, String keystorePath, String keystorePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException { SSLContext ctx;//from w w w. j a v a 2s . c o m try (FileInputStream tsf = new FileInputStream(truststorePath); FileInputStream ksf = new FileInputStream(keystorePath)) { ctx = SSLContext.getInstance("SSL"); KeyStore ts = KeyStore.getInstance("JKS"); ts.load(tsf, truststorePassword.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ts); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(ksf, keystorePassword.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, keystorePassword.toCharArray()); ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); } return ctx; }
From source file:org.apache.geode.internal.net.SocketCreator.java
private TrustManager[] getTrustManagers() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { TrustManager[] trustManagers = null; GfeConsoleReader consoleReader = GfeConsoleReaderFactory.getDefaultConsoleReader(); String trustStoreType = sslConfig.getTruststoreType(); if (StringUtils.isEmpty(trustStoreType)) { // read from console, default on empty if (consoleReader.isSupported()) { trustStoreType = consoleReader .readLine("Please enter the trustStoreType (javax.net.ssl.trustStoreType) : "); } else {/*from w ww.j ava2 s. co m*/ trustStoreType = KeyStore.getDefaultType(); } } KeyStore ts = KeyStore.getInstance(trustStoreType); String trustStorePath = sslConfig.getTruststore(); if (StringUtils.isEmpty(trustStorePath)) { if (consoleReader.isSupported()) { trustStorePath = consoleReader .readLine("Please enter the trustStore location (javax.net.ssl.trustStore) : "); } } FileInputStream fis = new FileInputStream(trustStorePath); String passwordString = sslConfig.getTruststorePassword(); char[] password = null; if (passwordString != null) { if (passwordString.trim().equals("")) { if (!StringUtils.isEmpty(passwordString)) { String toDecrypt = "encrypted(" + passwordString + ")"; passwordString = PasswordUtil.decrypt(toDecrypt); password = passwordString.toCharArray(); } // read from the console if (StringUtils.isEmpty(passwordString) && consoleReader.isSupported()) { password = consoleReader.readPassword( "Please enter password for trustStore (javax.net.ssl.trustStorePassword) : "); } } else { password = passwordString.toCharArray(); } } ts.load(fis, password); // default algorithm can be changed by setting property "ssl.TrustManagerFactory.algorithm" in // security properties TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ts); trustManagers = tmf.getTrustManagers(); // follow the security tip in java doc if (password != null) { java.util.Arrays.fill(password, ' '); } return trustManagers; }
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;/*from w ww . j a 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:org.codice.ddf.cxf.client.impl.SecureCxfClientFactoryImpl.java
@SuppressWarnings("squid:S3776") private void configureConduit(ClientConfiguration clientConfig) { HTTPConduit httpConduit = clientConfig.getHttpConduit(); if (httpConduit == null) { LOGGER.info("HTTPConduit was null for {}. Unable to configure security.", this); return;/*ww w . j a v a 2s . co m*/ } if (allowRedirects) { HTTPClientPolicy clientPolicy = httpConduit.getClient(); if (clientPolicy != null) { clientPolicy.setAutoRedirect(true); Bus bus = clientConfig.getBus(); if (bus != null) { bus.getProperties().put(AUTO_REDIRECT_ALLOW_REL_URI, true); bus.getProperties().put(AUTO_REDIRECT_MAX_SAME_URI_COUNT, getSameUriRedirectMax()); } } } TLSClientParameters tlsParams = httpConduit.getTlsClientParameters(); if (tlsParams == null) { tlsParams = new TLSClientParameters(); } tlsParams.setDisableCNCheck(disableCnCheck); tlsParams.setUseHttpsURLConnectionDefaultHostnameVerifier(!disableCnCheck); String cipherSuites = System.getProperty("https.cipherSuites"); if (cipherSuites != null) { tlsParams.setCipherSuites(Arrays.asList(cipherSuites.split(","))); } KeyStore keyStore = null; KeyStore trustStore = null; try { keyStore = SecurityConstants.newKeystore(); trustStore = SecurityConstants.newTruststore(); } catch (KeyStoreException e) { LOGGER.debug("Unable to create keystore instance of type {}", System.getProperty(SecurityConstants.KEYSTORE_TYPE), e); } Path keyStoreFile; if (keyInfo != null && StringUtils.isNotBlank(keyInfo.getKeystorePath())) { keyStoreFile = Paths.get(keyInfo.getKeystorePath()); } else { keyStoreFile = Paths.get(SecurityConstants.getKeystorePath()); } Path trustStoreFile = Paths.get(SecurityConstants.getTruststorePath()); String ddfHome = System.getProperty("ddf.home"); if (ddfHome != null) { Path ddfHomePath = Paths.get(ddfHome); if (!keyStoreFile.isAbsolute()) { keyStoreFile = Paths.get(ddfHomePath.toString(), keyStoreFile.toString()); } if (!trustStoreFile.isAbsolute()) { trustStoreFile = Paths.get(ddfHomePath.toString(), trustStoreFile.toString()); } } String keyStorePassword = SecurityConstants.getKeystorePassword(); String trustStorePassword = SecurityConstants.getTruststorePassword(); if (!Files.isReadable(keyStoreFile) || !Files.isReadable(trustStoreFile)) { LOGGER.debug("Unable to read system key/trust store files: [ {} ] [ {} ]", keyStoreFile, trustStoreFile); return; } try (InputStream kfis = Files.newInputStream(keyStoreFile)) { if (keyStore != null) { keyStore.load(kfis, keyStorePassword.toCharArray()); } } catch (NoSuchAlgorithmException | CertificateException | IOException e) { LOGGER.debug("Unable to load system key file.", e); } try (InputStream tfis = Files.newInputStream(trustStoreFile)) { if (trustStore != null) { trustStore.load(tfis, trustStorePassword.toCharArray()); } } catch (NoSuchAlgorithmException | CertificateException | IOException e) { LOGGER.debug("Unable to load system trust file.", e); } KeyManager[] keyManagers = null; try { KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, keyStorePassword.toCharArray()); keyManagers = keyManagerFactory.getKeyManagers(); tlsParams.setKeyManagers(keyManagers); } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException e) { LOGGER.debug("Unable to initialize KeyManagerFactory.", e); } TrustManager[] trustManagers = null; try { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); trustManagers = trustManagerFactory.getTrustManagers(); tlsParams.setTrustManagers(trustManagers); } catch (NoSuchAlgorithmException | KeyStoreException e) { LOGGER.debug("Unable to initialize TrustManagerFactory.", e); } if (keyInfo != null) { LOGGER.trace("Using keystore file: {}, alias: {}", keyStoreFile, keyInfo.getAlias()); tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(false); tlsParams.setCertAlias(keyInfo.getAlias()); try { if (keyManagers == null) { throw new KeyManagementException("keyManagers was null"); } boolean validProtocolFound = false; String validProtocolsStr = System.getProperty("jdk.tls.client.protocols"); if (StringUtils.isNotBlank(validProtocolsStr)) { String[] validProtocols = validProtocolsStr.split(","); for (String validProtocol : validProtocols) { if (validProtocol.equals(sslProtocol)) { validProtocolFound = true; break; } } if (!validProtocolFound) { LOGGER.error("{} is not in list of valid SSL protocols {}", sslProtocol, validProtocolsStr); } } else { validProtocolFound = true; } if (validProtocolFound) { tlsParams.setSSLSocketFactory( getSSLSocketFactory(sslProtocol, keyInfo.getAlias(), keyManagers, trustManagers)); } } catch (KeyManagementException | NoSuchAlgorithmException e) { LOGGER.debug("Unable to override default SSL Socket Factory", e); } } else { tlsParams.setUseHttpsURLConnectionDefaultSslSocketFactory(true); tlsParams.setCertAlias(SystemBaseUrl.INTERNAL.getHost()); } httpConduit.setTlsClientParameters(tlsParams); }
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 ww w . j a va2s.c o m*/ 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:com.datastax.loader.CqlDelimLoad.java
private SSLOptions createSSLOptions() throws KeyStoreException, FileNotFoundException, IOException, NoSuchAlgorithmException, KeyManagementException, CertificateException, UnrecoverableKeyException { TrustManagerFactory tmf = null; KeyStore tks = KeyStore.getInstance("JKS"); tks.load((InputStream) new FileInputStream(new File(truststorePath)), truststorePwd.toCharArray()); tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(tks);// ww w . j a v a 2 s .com KeyManagerFactory kmf = null; if (null != keystorePath) { KeyStore kks = KeyStore.getInstance("JKS"); kks.load((InputStream) new FileInputStream(new File(keystorePath)), keystorePwd.toCharArray()); kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(kks, keystorePwd.toCharArray()); } SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf != null ? kmf.getKeyManagers() : null, tmf != null ? tmf.getTrustManagers() : null, new SecureRandom()); return JdkSSLOptions.builder().withSSLContext(sslContext).build(); }
From source file:com.wso2.mobile.mdm.utils.ServerUtilities.java
public static HttpsURLConnection getTrustedConnection(Context context, HttpsURLConnection conn) { HttpsURLConnection urlConnection = conn; try {//w w w . ja v a 2s . c o m KeyStore localTrustStore; localTrustStore = KeyStore.getInstance("BKS"); InputStream in = context.getResources().openRawResource(R.raw.emm_truststore); localTrustStore.load(in, CommonUtilities.TRUSTSTORE_PASSWORD.toCharArray()); TrustManagerFactory tmf; tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(localTrustStore); SSLContext sslCtx; sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(null, tmf.getTrustManagers(), null); urlConnection.setSSLSocketFactory(sslCtx.getSocketFactory()); return urlConnection; } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } catch (CertificateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return null; } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return null; } catch (KeyStoreException e2) { // TODO Auto-generated catch block e2.printStackTrace(); return null; } }
From source file:org.wso2.carbon.identity.sso.agent.bean.SSOAgentConfig.java
private TrustManager[] doSSLVerification() throws Exception { TrustManager[] trustManagers = null; if (this.getEnableSSLVerification()) { TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(this.getKeyStore()); trustManagers = tmf.getTrustManagers(); } else {/* w ww .j a v a 2 s .c om*/ // Create a trust manager that does not validate certificate chains trustManagers = 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) { } } }; } return trustManagers; }
From source file:org.araqne.pkg.PackageManagerService.java
private byte[] download(PackageRepository repo, URL url) throws IOException, KeyStoreException, UnrecoverableKeyException, KeyManagementException { if (repo.isLocalFilesystem()) { FileInputStream stream = null; try {/*from ww w .j av a2 s. c om*/ File file = new File(url.toURI()); long length = file.length(); stream = new FileInputStream(file); byte[] b = new byte[(int) length]; stream.read(b); return b; } catch (URISyntaxException e) { e.printStackTrace(); return new byte[0]; } finally { if (stream != null) stream.close(); } } else if (repo.isHttps()) { ServiceReference<?> ref = bc.getServiceReference(KeyStoreManager.class.getName()); KeyStoreManager keyman = (KeyStoreManager) bc.getService(ref); try { TrustManagerFactory tmf = keyman.getTrustManagerFactory(repo.getTrustStoreAlias(), TrustManagerFactory.getDefaultAlgorithm()); KeyManagerFactory kmf = keyman.getKeyManagerFactory(repo.getKeyStoreAlias(), KeyManagerFactory.getDefaultAlgorithm()); HttpWagon.download(url, tmf, kmf); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return HttpWagon.download(url); } else if (repo.isAuthRequired()) return HttpWagon.download(url, true, repo.getAccount(), repo.getPassword()); return HttpWagon.download(url); }
From source file:edu.washington.shibboleth.attribute.resolver.provider.dataConnector.RwsDataConnector.java
/** * This sets the trust managers that will be used for all TLS and SSL connections to the ldap. This method will * remove any cached results and initialize the connection manager. * //from ww w . j a v a 2 s . c o m * @see #clearCache() * @see #setSslSocketFactory(SSLSocketFactory) * * @param tc <code>X509Credential</code> to create TrustManagers with */ public void setSslTrustManagers(X509Credential tc) { if (tc != null) { try { TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, null); for (X509Certificate c : tc.getEntityCertificateChain()) { keystore.setCertificateEntry("ldap_tls_trust_" + c.getSerialNumber(), c); } tmf.init(keystore); sslTrustManagers = tmf.getTrustManagers(); } catch (GeneralSecurityException e) { log.error("Error initializing trust managers", e); } catch (IOException e) { log.error("Error initializing trust managers", e); } } }