List of usage examples for javax.net.ssl TrustManagerFactory getDefaultAlgorithm
public static final String getDefaultAlgorithm()
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);/* ww w . ja v a 2 s .com*/ 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.mytalentfolio.h_daforum.CconnectToServer.java
/** * Creates a new instance of {@code TrustManagerFactory} from provided * {@code KeyStore}.//from ww w. j a v a 2 s . 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: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 av a 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:it.paolorendano.clm.AbstractCassandraDAO.java
/** * Gets the SSL context./*from w w w .j ava 2s . co m*/ * * @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 va 2s . 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 ww w . j a v 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; }
From source file:org.apache.nifi.processors.grpc.ListenGRPC.java
@OnScheduled public void startServer(final ProcessContext context) throws NoSuchAlgorithmException, IOException, KeyStoreException, CertificateException, UnrecoverableKeyException { final ComponentLog logger = getLogger(); // gather configured properties final Integer port = context.getProperty(PROP_SERVICE_PORT).asInteger(); final Boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean(); final Integer flowControlWindow = context.getProperty(PROP_FLOW_CONTROL_WINDOW).asDataSize(DataUnit.B) .intValue();//from w w w.ja v a 2 s.c o m final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue(); final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE) .asControllerService(SSLContextService.class); final SSLContext sslContext = sslContextService == null ? null : sslContextService.createSSLContext(SSLContextService.ClientAuth.NONE); final Pattern authorizedDnPattern = Pattern .compile(context.getProperty(PROP_AUTHORIZED_DN_PATTERN).getValue()); final FlowFileIngestServiceInterceptor callInterceptor = new FlowFileIngestServiceInterceptor(getLogger()); callInterceptor.enforceDNPattern(authorizedDnPattern); final FlowFileIngestService flowFileIngestService = new FlowFileIngestService(getLogger(), sessionFactoryReference, context); NettyServerBuilder serverBuilder = NettyServerBuilder.forPort(port) .addService(ServerInterceptors.intercept(flowFileIngestService, callInterceptor)) // default (de)compressor registries handle both plaintext and gzip compressed messages .compressorRegistry(CompressorRegistry.getDefaultInstance()) .decompressorRegistry(DecompressorRegistry.getDefaultInstance()) .flowControlWindow(flowControlWindow).maxMessageSize(maxMessageSize); if (useSecure && sslContext != null) { // construct key manager if (StringUtils.isBlank(sslContextService.getKeyStoreFile())) { throw new IllegalStateException( "SSL is enabled, but no keystore has been configured. You must configure a keystore."); } final KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm(), sslContext.getProvider()); final KeyStore keyStore = KeyStore.getInstance(sslContextService.getKeyStoreType()); try (final InputStream is = new FileInputStream(sslContextService.getKeyStoreFile())) { keyStore.load(is, sslContextService.getKeyStorePassword().toCharArray()); } keyManagerFactory.init(keyStore, sslContextService.getKeyStorePassword().toCharArray()); SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(keyManagerFactory); // if the trust store is configured, then client auth is required. if (StringUtils.isNotBlank(sslContextService.getTrustStoreFile())) { final TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm(), sslContext.getProvider()); final KeyStore trustStore = KeyStore.getInstance(sslContextService.getTrustStoreType()); try (final InputStream is = new FileInputStream(sslContextService.getTrustStoreFile())) { trustStore.load(is, sslContextService.getTrustStorePassword().toCharArray()); } trustManagerFactory.init(trustStore); sslContextBuilder = sslContextBuilder.trustManager(trustManagerFactory); sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE); } else { sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.NONE); } sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder); serverBuilder = serverBuilder.sslContext(sslContextBuilder.build()); } logger.info("Starting gRPC server on port: {}", new Object[] { port.toString() }); this.server = serverBuilder.build().start(); }
From source file:org.asynchttpclient.test.TestUtils.java
private static TrustManager[] createTrustManagers() throws GeneralSecurityException, IOException { KeyStore ks = KeyStore.getInstance("JKS"); try (InputStream keyStoreStream = TestUtils.class.getClassLoader() .getResourceAsStream("ssltest-keystore.jks")) { char[] keyStorePassword = "changeit".toCharArray(); ks.load(keyStoreStream, keyStorePassword); }//from w w w .j a v a2 s . co m assert (ks.size() > 0); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); return tmf.getTrustManagers(); }
From source file:com.vmware.identity.openidconnect.client.TestUtils.java
static VmdirClient createVMdirClient(AccessToken accessToken, String domainControllerFQDN, int domainControllerPort, KeyStore keyStore) throws Exception { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore);/*from www . j a v a 2 s .com*/ SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustManagerFactory.getTrustManagers(), null); VmdirClient vmdirClient = new VmdirClient(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); vmdirClient.setToken(restAccessToken); return vmdirClient; }
From source file:org.apache.synapse.transport.nhttp.HttpCoreNIOSSLSender.java
private SSLContext createSSLContext(OMElement keyStoreElt, OMElement trustStoreElt, boolean novalidatecert) throws AxisFault { KeyManager[] keymanagers = null; TrustManager[] trustManagers = null; if (keyStoreElt != null) { String location = keyStoreElt.getFirstChildWithName(new QName("Location")).getText(); String type = keyStoreElt.getFirstChildWithName(new QName("Type")).getText(); String storePassword = keyStoreElt.getFirstChildWithName(new QName("Password")).getText(); String keyPassword = keyStoreElt.getFirstChildWithName(new QName("KeyPassword")).getText(); FileInputStream fis = null; try {// ww w . ja va2s .com KeyStore keyStore = KeyStore.getInstance(type); fis = new FileInputStream(location); log.info("Loading Identity Keystore from : " + location); keyStore.load(fis, storePassword.toCharArray()); KeyManagerFactory kmfactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmfactory.init(keyStore, keyPassword.toCharArray()); keymanagers = kmfactory.getKeyManagers(); } catch (GeneralSecurityException gse) { log.error("Error loading Keystore : " + location, gse); throw new AxisFault("Error loading Keystore : " + location, gse); } catch (IOException ioe) { log.error("Error opening Keystore : " + location, ioe); throw new AxisFault("Error opening Keystore : " + location, ioe); } finally { if (fis != null) { try { fis.close(); } catch (IOException ignore) { } } } } if (trustStoreElt != null) { if (novalidatecert) { log.warn("Ignoring novalidatecert parameter since a truststore has been specified"); } String location = trustStoreElt.getFirstChildWithName(new QName("Location")).getText(); String type = trustStoreElt.getFirstChildWithName(new QName("Type")).getText(); String storePassword = trustStoreElt.getFirstChildWithName(new QName("Password")).getText(); FileInputStream fis = null; try { KeyStore trustStore = KeyStore.getInstance(type); fis = new FileInputStream(location); log.info("Loading Trust Keystore from : " + location); trustStore.load(fis, storePassword.toCharArray()); TrustManagerFactory trustManagerfactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerfactory.init(trustStore); trustManagers = trustManagerfactory.getTrustManagers(); } catch (GeneralSecurityException gse) { log.error("Error loading Key store : " + location, gse); throw new AxisFault("Error loading Key store : " + location, gse); } catch (IOException ioe) { log.error("Error opening Key store : " + location, ioe); throw new AxisFault("Error opening Key store : " + location, ioe); } finally { if (fis != null) { try { fis.close(); } catch (IOException ignore) { } } } } else if (novalidatecert) { log.warn("Server certificate validation (trust) has been disabled. " + "DO NOT USE IN PRODUCTION!"); trustManagers = new TrustManager[] { new NoValidateCertTrustManager() }; } try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(keymanagers, trustManagers, null); return sslcontext; } catch (GeneralSecurityException gse) { log.error("Unable to create SSL context with the given configuration", gse); throw new AxisFault("Unable to create SSL context with the given configuration", gse); } }