List of usage examples for javax.net.ssl TrustManagerFactory getInstance
public static final TrustManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException
TrustManagerFactory
object that acts as a factory for trust managers. From source file:org.gvnix.service.roo.addon.addon.security.SecurityServiceImpl.java
/** * Get certificates in the chain of the host server and import them. * <p>/*from ww w. jav a 2 s . c om*/ * Tries to get the certificates in the certificates chain of the host * server and import them to: * <ol> * <li>A custom keystore in <code>SRC_MAIN_RESOURCES/gvnix-cacerts</code></li> * <li>The JVM cacerts keystore in * <code>$JAVA_HOME/jre/lib/security/cacerts</code>. Here we can have a * problem if JVM <code>cacerts</code> file is not writable by the user due * to file permissions. In this case we throw an exception informing about * the error.</li> * </ol> * </p> * <p> * With that operation we can try again to get the WSDL.<br/> * Also it exports the chain certificates to <code>.cer</code> files in * <code>SRC_MAIN_RESOURCES</code>, so the developer can distribute them for * its installation in other environments or just in case we reach the * problem with the JVM <code>cacerts</code> file permissions. * </p> * * @see GvNix509TrustManager#saveCertFile(String, X509Certificate, * FileManager, PathResolver) * @see <a href= * "http://download.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html" * >Java SE keytool</a>. */ protected Document installCertificates(String loc, String pass) throws NoSuchAlgorithmException, KeyStoreException, Exception, KeyManagementException, MalformedURLException, IOException, UnknownHostException, SocketException, SAXException { // Create a SSL context SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); // Passphrase of the keystore: "changeit" by default char[] passArray = (StringUtils.isNotBlank(pass) ? pass.toCharArray() : "changeit".toCharArray()); // Get the project keystore and copy it from JVM if not exists File keystore = getProjectKeystore(); tmf.init(GvNix509TrustManager.loadKeyStore(keystore, passArray)); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; GvNix509TrustManager tm = new GvNix509TrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); // Open URL location (default 443 port if not defined) URL url = new URL(loc); String host = url.getHost(); int port = url.getPort() == -1 ? 443 : url.getPort(); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); Document doc = null; try { socket.startHandshake(); URLConnection connection = url.openConnection(); if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setSSLSocketFactory(factory); } doc = XmlUtils.getDocumentBuilder().parse(connection.getInputStream()); socket.close(); } catch (SSLException ssle) { // Get needed certificates for this host getCerts(tm, host, keystore, passArray); doc = getWsdl(loc, pass); } catch (IOException ioe) { invalidHostCert(passArray, keystore, tm, host); } Validate.notNull(doc, "No valid document format"); return doc; }
From source file:com.vmware.identity.openidconnect.client.TestUtils.java
static IdmClient createIdmClient(AccessToken accessToken, String domainControllerFQDN, int domainControllerPort, KeyStore keyStore) throws Exception { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore);//w w w.jav a 2 s . com SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustManagerFactory.getTrustManagers(), null); IdmClient idmClient = new IdmClient(domainControllerFQDN, domainControllerPort, new DefaultHostnameVerifier(), sslContext); com.vmware.identity.rest.core.client.AccessToken restAccessToken = new com.vmware.identity.rest.core.client.AccessToken( accessToken.getValue(), com.vmware.identity.rest.core.client.AccessToken.Type.JWT); idmClient.setToken(restAccessToken); return idmClient; }
From source file:org.jboss.as.test.integration.security.loginmodules.RemotingLoginModuleTestCase.java
/** * Configure {@link SSLContext} and create EJB client properties. * * @param clientName//from w ww . j av a 2 s. c o m * @return * @throws Exception */ private Properties configureEjbClient(String clientName) throws Exception { // create new SSLContext based on client keystore and truststore and use this SSLContext instance as a default for this test KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init( KeyStoreUtil.getKeyStore(getClientKeystoreFile(clientName), KEYSTORE_PASSWORD.toCharArray()), KEYSTORE_PASSWORD.toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory .init(KeyStoreUtil.getKeyStore(CLIENTS_TRUSTSTORE_FILE, KEYSTORE_PASSWORD.toCharArray())); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); SSLContext.setDefault(sslContext); final Properties env = new Properties(); env.put("java.naming.factory.initial", "org.jboss.naming.remote.client.InitialContextFactory"); env.put("java.naming.provider.url", "remote://" + mgmtClient.getMgmtAddress() + ":" + REMOTING_PORT_TEST); env.put("jboss.naming.client.ejb.context", "true"); env.put("jboss.naming.client.connect.options.org.xnio.Options.SASL_POLICY_NOPLAINTEXT", "false"); env.put(Context.SECURITY_PRINCIPAL, "admin"); env.put(Context.SECURITY_CREDENTIALS, "testing"); // SSL related config parameters env.put("jboss.naming.client.remote.connectionprovider.create.options.org.xnio.Options.SSL_ENABLED", "true"); env.put("jboss.naming.client.connect.options.org.xnio.Options.SSL_STARTTLS", "true"); return env; }
From source file:mitm.common.security.ca.handlers.ejbca.EJBCACertificateRequestHandler.java
private EjbcaWS getEjbcaWS() throws CAException { if (ejbcaWS == null) { try {// w ww.ja v a 2s .c o m JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean(); factory.setServiceClass(EjbcaWS.class); factory.setAddress(requestHandlerSettings.getWebServiceURL().toExternalForm()); factory.setServiceName(EJBCAConst.SERVICE_NAME); EjbcaWS localEjbcaWS = (EjbcaWS) factory.create(); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); char[] password = requestHandlerSettings.getKeyStorePassword() != null ? requestHandlerSettings.getKeyStorePassword().toCharArray() : null; keyManagerFactory.init(requestHandlerSettings.getKeyStore(), password); KeyManager[] keyManagers = keyManagerFactory.getKeyManagers(); Client proxy = ClientProxy.getClient(localEjbcaWS); TLSClientParameters tlsClientParameters = new TLSClientParameters(); tlsClientParameters.setDisableCNCheck(requestHandlerSettings.isDisableCNCheck()); if (requestHandlerSettings.isSkipCertificateCheck()) { /* * Use a TrustManager that skips all checks */ tlsClientParameters.setTrustManagers(new TrustManager[] { new TrustAllX509TrustManager() }); } else { KeyStore trustStore = requestHandlerSettings.getTrustStore(); if (trustStore != null) { /* * Use the provided trust store */ TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); tlsClientParameters.setTrustManagers(trustManagerFactory.getTrustManagers()); } } tlsClientParameters.setKeyManagers(keyManagers); HTTPConduit conduit = (HTTPConduit) proxy.getConduit(); conduit.setTlsClientParameters(tlsClientParameters); ejbcaWS = localEjbcaWS; } catch (NoSuchAlgorithmException e) { throw new CAException(e); } catch (UnrecoverableKeyException e) { throw new CAException(e); } catch (KeyStoreException e) { throw new CAException(e); } } return ejbcaWS; }
From source file:com.openshift.restclient.ClientBuilder.java
private TrustManagerFactory initTrustManagerFactory(String alias, X509Certificate cert, Collection<X509Certificate> certs) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); if (alias != null && (cert != null || certs != null)) { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); // need this load to initialize the key store, and allow for the subsequent set certificate entry ks.load(null, null);//from w ww . j a v a 2 s .co m if (cert != null) { cert.checkValidity(); ks.setCertificateEntry(alias, cert); } if (certs != null) { int i = 0; for (X509Certificate x509 : certs) { x509.checkValidity(); ks.setCertificateEntry(alias + i, x509); i++; } } // testing has proven that you can only call init() once for a TrustManagerFactory wrt loading certs // from the KeyStore ... subsequent KeyStore.setCertificateEntry / TrustManagerFactory.init calls are // ignored. // So if a specific cert is required to validate this connection's communication with the server, add it up front // in the ctor. trustManagerFactory.init(ks); } else { trustManagerFactory.init((KeyStore) null); } return trustManagerFactory; }
From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java
private static SSLContext sslContext() { final String property = SettingsManager.settings().ssl(); if (property != null && !property.isEmpty() && !"null".equals(property)) { if ("trustanything".equals(property)) { try { return SSLContexts.custom().loadTrustMaterial(KeyStore.getInstance(KeyStore.getDefaultType()), new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; }//from www .j a va 2 s.c o m }).build(); } catch (Throwable t) { LogsServer.instance().exception(t); } } else { try { String location = property; location = location.equals("compatible") ? "https://raw.githubusercontent.com/bagder/ca-bundle/master/ca-bundle.crt" : location; File cachedPemFile = new File("./pemfile_cached"); boolean remote = location.startsWith("https://") || location.startsWith("http://"); if (remote && cachedPemFile.exists() && (System.currentTimeMillis() - cachedPemFile.lastModified() < 48 * 60 * 60 * 1000)) { location = cachedPemFile.getAbsolutePath(); remote = false; } String pemBlocks = null; if (remote) { HttpURLConnection remotePemFile = (HttpURLConnection) StreamHandler .defaultConnection(new URL(location)); remotePemFile.setRequestMethod("GET"); remotePemFile.connect(); pemBlocks = Util.toString(remotePemFile.getInputStream(), Util.charset(remotePemFile)); cachedPemFile.delete(); Files.write(Paths.get(cachedPemFile.getAbsolutePath()), pemBlocks.getBytes("utf-8")); } else { pemBlocks = new String(Files.readAllBytes(Paths.get(new File(location).getAbsolutePath())), "utf-8"); } KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Matcher matcher = pemBlock.matcher(pemBlocks); boolean found = false; while (matcher.find()) { String pemBlock = matcher.group(1).replaceAll("[\\n\\r]+", ""); ByteArrayInputStream byteStream = new ByteArrayInputStream( Base64.getDecoder().decode(pemBlock)); java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) cf .generateCertificate(byteStream); String alias = cert.getSubjectX500Principal().getName("RFC2253"); if (alias != null && !keyStore.containsAlias(alias)) { found = true; keyStore.setCertificateEntry(alias, cert); } } if (found) { KeyManagerFactory keyManager = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManager.init(keyStore, null); TrustManagerFactory trustManager = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManager.init(keyStore); SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null); return context; } } catch (Throwable t) { LogsServer.instance().exception(t); } } } return SSLContexts.createSystemDefault(); }
From source file:com.mytalentfolio.h_daforum.CconnectToServer.java
/** * Creates a new instance of {@code TrustManagerFactory} from provided * {@code KeyStore}.//from w ww . j a v a 2s . c o m * * @param keyStore * the KeyStore to get the TrustManagerFactory * @return the new {@code TrustManagerFactory} instance. * @throws KeyStoreException * if an error occurred during the creation of the new KeyStore. * @throws NoSuchAlgorithmException * if the required algorithm is not available. * */ private TrustManagerFactory getTrustManager(KeyStore keyStore) throws NoSuchAlgorithmException, KeyStoreException { // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); return tmf; }
From source file:it.paolorendano.clm.AbstractCassandraDAO.java
/** * Gets the SSL context./*from w ww . j a v a 2s . com*/ * * @param truststorePath the truststore path * @param truststorePassword the truststore password * @param keystorePath the keystore path * @param keystorePassword the keystore password * @return the SSL context * @throws NoSuchAlgorithmException the no such algorithm exception * @throws KeyStoreException the key store exception * @throws CertificateException the certificate exception * @throws IOException Signals that an I/O exception has occurred. * @throws UnrecoverableKeyException the unrecoverable key exception * @throws KeyManagementException the key management exception */ private static SSLContext getSSLContext(String truststorePath, String truststorePassword, String keystorePath, String keystorePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException { /* taken from http://www.datastax.com/dev/blog/accessing-secure-dse-clusters-with-cql-native-protocol */ FileInputStream tsf = new FileInputStream(truststorePath); FileInputStream ksf = new FileInputStream(keystorePath); SSLContext 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:com.comcast.cdn.traffic_control.traffic_router.core.external.RouterTest.java
@Before public void before() throws Exception { ObjectMapper objectMapper = new ObjectMapper(new JsonFactory()); String resourcePath = "internal/api/1.3/steering.json"; InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath); if (inputStream == null) { fail("Could not find file '" + resourcePath + "' needed for test from the current classpath as a resource!"); }//from ww w. j a v a2 s. c om Set<String> steeringDeliveryServices = new HashSet<String>(); JsonNode steeringData = objectMapper.readTree(inputStream).get("response"); Iterator<JsonNode> elements = steeringData.elements(); while (elements.hasNext()) { JsonNode ds = elements.next(); String dsId = ds.get("deliveryService").asText(); steeringDeliveryServices.add(dsId); } resourcePath = "publish/CrConfig.json"; inputStream = getClass().getClassLoader().getResourceAsStream(resourcePath); if (inputStream == null) { fail("Could not find file '" + resourcePath + "' needed for test from the current classpath as a resource!"); } JsonNode jsonNode = objectMapper.readTree(inputStream); deliveryServiceId = null; Iterator<String> deliveryServices = jsonNode.get("deliveryServices").fieldNames(); while (deliveryServices.hasNext()) { String dsId = deliveryServices.next(); if (steeringDeliveryServices.contains(dsId)) { continue; } JsonNode deliveryServiceNode = jsonNode.get("deliveryServices").get(dsId); Iterator<JsonNode> matchsets = deliveryServiceNode.get("matchsets").iterator(); while (matchsets.hasNext() && deliveryServiceId == null) { if ("HTTP".equals(matchsets.next().get("protocol").asText())) { final boolean sslEnabled = JsonUtils.optBoolean(deliveryServiceNode, "sslEnabled"); if (!sslEnabled) { deliveryServiceId = dsId; deliveryServiceDomain = deliveryServiceNode.get("domains").get(0).asText(); } } } } assertThat(deliveryServiceId, not(nullValue())); assertThat(deliveryServiceDomain, not(nullValue())); assertThat(httpsOnlyId, not(nullValue())); assertThat(httpsOnlyDomain, not(nullValue())); Iterator<String> cacheIds = jsonNode.get("contentServers").fieldNames(); while (cacheIds.hasNext()) { String cacheId = cacheIds.next(); JsonNode cacheNode = jsonNode.get("contentServers").get(cacheId); if (!cacheNode.has("deliveryServices")) { continue; } if (cacheNode.get("deliveryServices").has(deliveryServiceId)) { int port = cacheNode.get("port").asInt(); String portText = (port == 80) ? "" : ":" + port; validLocations.add("http://" + cacheId + "." + deliveryServiceDomain + portText + "/stuff?fakeClientIpAddress=12.34.56.78"); validLocations.add("http://" + cacheId + "." + deliveryServiceDomain + portText + "/stuff?fakeClientIpAddress=12.34.56.78&format=json"); } if (cacheNode.get("deliveryServices").has(httpsOnlyId)) { int port = cacheNode.has("httpsPort") ? cacheNode.get("httpsPort").asInt(443) : 443; String portText = (port == 443) ? "" : ":" + port; httpsOnlyLocations.add("https://" + cacheId + "." + httpsOnlyDomain + portText + "/stuff?fakeClientIpAddress=12.34.56.78"); } if (cacheNode.get("deliveryServices").has(httpsNoCertsId)) { int port = cacheNode.has("httpsPort") ? cacheNode.get("httpsPort").asInt(443) : 443; String portText = (port == 443) ? "" : ":" + port; httpsNoCertsLocations.add("https://" + cacheId + "." + httpsNoCertsDomain + portText + "/stuff?fakeClientIpAddress=12.34.56.78"); } if (cacheNode.get("deliveryServices").has(httpAndHttpsId)) { int port = cacheNode.has("httpsPort") ? cacheNode.get("httpsPort").asInt(443) : 443; String portText = (port == 443) ? "" : ":" + port; httpAndHttpsLocations.add("https://" + cacheId + "." + httpAndHttpsDomain + portText + "/stuff?fakeClientIpAddress=12.34.56.78"); port = cacheNode.has("port") ? cacheNode.get("port").asInt(80) : 80; portText = (port == 80) ? "" : ":" + port; httpAndHttpsLocations.add("http://" + cacheId + "." + httpAndHttpsDomain + portText + "/stuff?fakeClientIpAddress=12.34.56.78"); } if (cacheNode.get("deliveryServices").has(httpToHttpsId)) { int port = cacheNode.has("httpsPort") ? cacheNode.get("httpsPort").asInt(443) : 443; String portText = (port == 443) ? "" : ":" + port; httpToHttpsLocations.add("https://" + cacheId + "." + httpToHttpsDomain + portText + "/stuff?fakeClientIpAddress=12.34.56.78"); } if (cacheNode.get("deliveryServices").has(httpOnlyId)) { int port = cacheNode.has("port") ? cacheNode.get("port").asInt(80) : 80; String portText = (port == 80) ? "" : ":" + port; httpOnlyLocations.add("http://" + cacheId + "." + httpOnlyDomain + portText + "/stuff?fakeClientIpAddress=12.34.56.78"); } } assertThat(validLocations.isEmpty(), equalTo(false)); assertThat(httpsOnlyLocations.isEmpty(), equalTo(false)); trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream keystoreStream = getClass().getClassLoader().getResourceAsStream("keystore.jks"); trustStore.load(keystoreStream, "changeit".toCharArray()); TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()).init(trustStore); httpClient = HttpClientBuilder.create() .setSSLSocketFactory(new ClientSslSocketFactory("tr.https-only-test.thecdn.example.com")) .setSSLHostnameVerifier(new TestHostnameVerifier()).disableRedirectHandling().build(); }
From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java
private boolean loadKeyStores() { // Maintain a local copy of the trust and key managers in case anything goes wrong TrustManagerFactory tmf;/*from w w w. j av a 2 s .co m*/ KeyManagerFactory kmf; try { String ksLocation = System.getProperty("javax.net.ssl.keyStore", DEFAULT_KS_FILE.toString()); String tsLocation = System.getProperty("javax.net.ssl.trustStore", DEFAULT_KS_FILE.toString()); char[] ksPwd = System.getProperty("javax.net.ssl.keyStorePassword", DEFAULT_KS_PASSWORD).toCharArray(); char[] tsPwd = System.getProperty("javax.net.ssl.trustStorePassword", DEFAULT_KS_PASSWORD) .toCharArray(); tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType()); try (FileInputStream fileInputStream = new FileInputStream(tsLocation)) { ts.load(fileInputStream, tsPwd); } tmf.init(ts); kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); try (FileInputStream fileInputStream = new FileInputStream(ksLocation)) { ks.load(fileInputStream, ksPwd); } kmf.init(ks, ksPwd); if (log.isInfoEnabled()) { logKeyStore(ks, ksLocation, ksPwd); } } catch (FileNotFoundException e) { log.warn("Disabling TLS for intra-cluster messaging; Could not load cluster key store: {}", e.getMessage()); return TLS_DISABLED; } catch (Exception e) { //TODO we might want to catch exceptions more specifically log.error("Error loading key store; disabling TLS for intra-cluster messaging", e); return TLS_DISABLED; } this.trustManager = tmf; this.keyManager = kmf; return TLS_ENABLED; }