List of usage examples for javax.net.ssl SSLContext getSocketFactory
public final SSLSocketFactory getSocketFactory()
From source file:org.hyperic.hq.plugin.appha.VSphereUtil.java
private static void configureSSLKeystore() { AgentKeystoreConfig keystoreConfig = new AgentKeystoreConfig(); SSLProvider sslProvider = new DefaultSSLProviderImpl(keystoreConfig, keystoreConfig.isAcceptUnverifiedCert()); SSLContext sslContext = sslProvider.getSSLContext(); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(new AllowAllHostnameVerifier()); }
From source file:org.miloss.nexuscloner.Main.java
private static void initSsl() throws Exception { TrustManager[] trustall = new TrustManager[] { new X509TrustManager() { @Override/* www .j a v a 2s. c o m*/ public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { System.out.println("Trust no one"); } @Override public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { System.out.println("Trust no one"); } @Override public X509Certificate[] getAcceptedIssuers() { System.out.println("Trust no one"); return null; } } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustall, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); }
From source file:io.fabric8.apiman.gateway.ApimanGatewayStarter.java
private static URL waitForDependency(URL url, String serviceName, String key, String value, String username, String password) throws InterruptedException { boolean isFoundRunningService = false; ObjectMapper mapper = new ObjectMapper(); int counter = 0; URL endpoint = null;/*from ww w. j a va 2 s. c o m*/ while (!isFoundRunningService) { endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort())); if (endpoint != null) { String isLive = null; try { URL statusURL = new URL(endpoint.toExternalForm() + url.getPath()); HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection(); urlConnection.setConnectTimeout(500); if (urlConnection instanceof HttpsURLConnection) { try { KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(TRUSTSTORE_PATH, TRUSTSTORE_PASSWORD_PATH); TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo); KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(CLIENT_KEYSTORE_PATH, CLIENT_KEYSTORE_PASSWORD_PATH); KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo); final SSLContext sc = SSLContext.getInstance("TLS"); sc.init(kms, tms, new java.security.SecureRandom()); final SSLSocketFactory socketFactory = sc.getSocketFactory(); HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory); HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection; httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier()); httpsConnection.setSSLSocketFactory(socketFactory); } catch (Exception e) { log.error(e.getMessage(), e); throw e; } } if (Utils.isNotNullOrEmpty(username)) { String encoded = Base64.getEncoder() .encodeToString((username + ":" + password).getBytes("UTF-8")); log.info(username + ":******"); urlConnection.setRequestProperty("Authorization", "Basic " + encoded); } isLive = IOUtils.toString(urlConnection.getInputStream()); Map<String, Object> esResponse = mapper.readValue(isLive, new TypeReference<Map<String, Object>>() { }); if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) { isFoundRunningService = true; } else { if (counter % 10 == 0) log.info(endpoint.toExternalForm() + " not yet up (host=" + endpoint.getHost() + ")" + isLive); } } catch (Exception e) { if (counter % 10 == 0) log.info(endpoint.toExternalForm() + " not yet up. (host=" + endpoint.getHost() + ")" + e.getMessage()); } } else { if (counter % 10 == 0) log.info("Could not find " + serviceName + " in namespace, waiting.."); } counter++; Thread.sleep(1000l); } return endpoint; }
From source file:org.signserver.client.cli.defaultimpl.KeyStoreOptions.java
private static void setDefaultSocketFactory(final KeyStore truststore, final KeyStore keystore, String keyAlias, char[] keystorePassword) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnrecoverableKeyException { final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(truststore);// w ww .ja v a 2 s.c o m final KeyManager[] keyManagers; if (keystore == null) { keyManagers = null; } else { if (keyAlias == null) { keyAlias = keystore.aliases().nextElement(); } final KeyManagerFactory kKeyManagerFactory = KeyManagerFactory.getInstance("SunX509"); kKeyManagerFactory.init(keystore, keystorePassword); keyManagers = kKeyManagerFactory.getKeyManagers(); for (int i = 0; i < keyManagers.length; i++) { if (keyManagers[i] instanceof X509KeyManager) { keyManagers[i] = new AliasKeyManager((X509KeyManager) keyManagers[i], keyAlias); } } } final SSLContext context = SSLContext.getInstance("TLS"); context.init(keyManagers, tmf.getTrustManagers(), new SecureRandom()); SSLSocketFactory factory = context.getSocketFactory(); HttpsURLConnection.setDefaultSSLSocketFactory(factory); }
From source file:com.wisdombud.right.client.common.HttpKit.java
private static SSLSocketFactory initSSLSocketFactory() { try {/* w w w . j a v a2 s .c om*/ final TrustManager[] tm = { new HttpKit().new TrustAnyTrustManager() }; final SSLContext sslContext = SSLContext.getInstance("TLS"); // ("TLS", // "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); return sslContext.getSocketFactory(); } catch (final Exception e) { throw new RuntimeException(e); } }
From source file:org.moe.cli.utils.GrabUtils.java
/** * Download file from remote/*from ww w .j av a 2 s. co m*/ * @param link address of remote file * @param output symbolic link to the local file system where the downloaded file will be stored * @throws FileAlreadyExistsException if output file has already exists * @throws FileNotFoundException if link isn't present * @throws UnsupportedTypeException if URI links to file with unsupported type * @throws IOException if operation couldn't be successfully completed because of other reasons */ public static void downloadFileFromRemote(@NonNull URI link, @NonNull File output) throws FileAlreadyExistsException, FileNotFoundException, UnsupportedTypeException, IOException { if (output.exists()) { throw new FileAlreadyExistsException(output.toString() + " already exists!"); } String scheme = link.getScheme(); if (scheme == null) { throw new UnsupportedTypeException("Scheme should not be null!"); } else if (scheme.equals("https")) { // Create a new trust manager that trust all certificates 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) { } } }; // Activate the new trust manager try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); } catch (Exception e) { throw new IOException(e); } } URL url = link.normalize().toURL(); FileUtils.copyURLToFile(url, output); //TODO: Timeout?... }
From source file:io.fabric8.apiman.ApimanStarter.java
private static URL waitForDependency(URL url, String path, String serviceName, String key, String value, String username, String password) throws InterruptedException { boolean isFoundRunningService = false; ObjectMapper mapper = new ObjectMapper(); int counter = 0; URL endpoint = null;/* w ww. j a v a 2s .c o m*/ while (!isFoundRunningService) { endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort())); if (endpoint != null) { String isLive = null; try { URL statusURL = new URL(endpoint.toExternalForm() + path); HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection(); urlConnection.setConnectTimeout(500); if (urlConnection instanceof HttpsURLConnection) { try { KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(ApimanStarter.TRUSTSTORE_PATH, ApimanStarter.TRUSTSTORE_PASSWORD_PATH); TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo); KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info( ApimanStarter.CLIENT_KEYSTORE_PATH, ApimanStarter.CLIENT_KEYSTORE_PASSWORD_PATH); KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo); final SSLContext sc = SSLContext.getInstance("TLS"); sc.init(kms, tms, new java.security.SecureRandom()); final SSLSocketFactory socketFactory = sc.getSocketFactory(); HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory); HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection; httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier()); httpsConnection.setSSLSocketFactory(socketFactory); } catch (Exception e) { log.error(e.getMessage(), e); throw e; } } if (Utils.isNotNullOrEmpty(username)) { String encoded = Base64.getEncoder() .encodeToString((username + ":" + password).getBytes("UTF-8")); urlConnection.setRequestProperty("Authorization", "Basic " + encoded); log.info(username + ":" + "*****"); } isLive = IOUtils.toString(urlConnection.getInputStream()); Map<String, Object> esResponse = mapper.readValue(isLive, new TypeReference<Map<String, Object>>() { }); if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) { isFoundRunningService = true; } else { if (counter % 10 == 0) log.info(endpoint.toExternalForm() + " not yet up. " + isLive); } } catch (Exception e) { if (counter % 10 == 0) log.info(endpoint.toExternalForm() + " not yet up. " + e.getMessage()); } } else { if (counter % 10 == 0) log.info("Could not find " + serviceName + " in namespace, waiting.."); } counter++; Thread.sleep(1000l); } return endpoint; }
From source file:ddf.security.common.util.CommonSSLFactory.java
/** * Creates a new SSLSocketFactory from a truststore and keystore. This is used during SSL * communication.//from w ww. j ava 2s. co m * * @param trustStoreLoc * File path to the truststore. * @param trustStorePass * Password to the truststore. * @param keyStoreLoc * File path to the keystore. * @param keyStorePass * Password to the keystore. * @return new SSLSocketFactory instance containing the trust and key stores. * @throws IOException */ public static SSLSocketFactory createSocket(String trustStoreLoc, String trustStorePass, String keyStoreLoc, String keyStorePass) throws IOException { String methodName = "createSocket"; logger.debug("ENTERING: " + methodName); try { logger.debug("trustStoreLoc = " + trustStoreLoc); FileInputStream trustFIS = new FileInputStream(trustStoreLoc); logger.debug("keyStoreLoc = " + keyStoreLoc); FileInputStream keyFIS = new FileInputStream(keyStoreLoc); // truststore stuff KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); try { logger.debug("Loading trustStore"); trustStore.load(trustFIS, trustStorePass.toCharArray()); } catch (CertificateException e) { throw new IOException("Unable to load certificates from truststore. " + trustStoreLoc, e); } finally { IOUtils.closeQuietly(trustFIS); } TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustStore); logger.debug("trust manager factory initialized"); // keystore stuff KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); try { logger.debug("Loading keyStore"); keyStore.load(keyFIS, keyStorePass.toCharArray()); } catch (CertificateException e) { throw new IOException("Unable to load certificates from keystore. " + keyStoreLoc, e); } finally { IOUtils.closeQuietly(keyFIS); } KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, keyStorePass.toCharArray()); logger.debug("key manager factory initialized"); // ssl context SSLContext sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); sslCtx.getDefaultSSLParameters().setNeedClientAuth(true); sslCtx.getDefaultSSLParameters().setWantClientAuth(true); logger.debug(exiting + methodName); return sslCtx.getSocketFactory(); } catch (KeyManagementException e) { logger.debug(exiting + methodName); throw new IOException("Unable to initialize the SSL context.", e); } catch (NoSuchAlgorithmException e) { logger.debug(exiting + methodName); throw new IOException( "Problems creating SSL socket. Usually this is " + "referring to the certificate sent by the server not being trusted by the client.", e); } catch (UnrecoverableKeyException e) { logger.debug(exiting + methodName); throw new IOException("Unable to load keystore. " + keyStoreLoc, e); } catch (KeyStoreException e) { logger.debug(exiting + methodName); throw new IOException("Unable to read keystore. " + keyStoreLoc, e); } }
From source file:com.longtime.ajy.support.weixin.HttpsKit.java
/** * ??Get//from w w w .j av a 2s . co m * * @param url * @return * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws IOException * @throws KeyManagementException */ public static String get(String url) {//throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException { InputStream in = null; HttpsURLConnection http = null; try { StringBuffer bufferRes = null; TrustManager[] tm = { new MyX509TrustManager() }; SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE"); sslContext.init(null, tm, new java.security.SecureRandom()); // SSLContextSSLSocketFactory SSLSocketFactory ssf = sslContext.getSocketFactory(); URL urlGet = new URL(url); http = (HttpsURLConnection) urlGet.openConnection(); // http.setConnectTimeout(TIME_OUT_CONNECT); // ? --?? http.setReadTimeout(TIME_OUT_READ); http.setRequestMethod("GET"); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setSSLSocketFactory(ssf); http.setDoOutput(true); http.setDoInput(true); http.connect(); in = http.getInputStream(); BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET)); String valueString = null; bufferRes = new StringBuffer(); while ((valueString = read.readLine()) != null) { bufferRes.append(valueString); } return bufferRes.toString(); } catch (Exception e) { logger.error(String.format("HTTP GET url=[%s] due to fail.", url), e); } finally { if (null != in) { try { in.close(); } catch (IOException e) { logger.error(String.format("HTTP GET url=[%s] close inputstream due to fail.", url), e); } } if (http != null) { // http.disconnect(); } } return StringUtils.EMPTY; }
From source file:io.apiman.gateway.platforms.servlet.connectors.ssl.SSLSessionStrategyFactory.java
/** * Build an {@link SSLSessionStrategy}.//from w w w.ja v a2 s .c o m * * @param trustStore the trust store * @param trustStorePassword the truststore password (if any) * @param keyStore the keystore * @param keyStorePassword the keystore password (if any) * @param keyAliases the key aliases that are candidates for use (if any) * @param keyPassword the key password (if any) * @param allowedProtocols the allowed transport protocols. * <strong><em>Avoid specifying insecure protocols</em></strong> * @param allowedCiphers allowed crypto ciphersuites, <tt>null</tt> to use system defaults * @param trustSelfSigned true if self signed certificates can be trusted. * <strong><em>Use with caution</em></strong> * @param allowAnyHostname true if any hostname can be connected to (i.e. does not need to match * certificate hostname). <strong><em>Do not use in production</em></strong> * @return the connection socket factory * @throws NoSuchAlgorithmException if the selected algorithm is not available on the system * @throws KeyStoreException if there was a problem with the keystore * @throws CertificateException if there was a problem with the certificate * @throws IOException if the truststore could not be found or was invalid * @throws KeyManagementException if there is a problem with keys * @throws UnrecoverableKeyException if the key cannot be recovered */ public static SSLSessionStrategy build(String trustStore, String trustStorePassword, String keyStore, String keyStorePassword, String[] keyAliases, String keyPassword, String[] allowedProtocols, String[] allowedCiphers, boolean allowAnyHostname, boolean trustSelfSigned) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, KeyManagementException, UnrecoverableKeyException { Args.notNull(allowedProtocols, "Allowed protocols"); //$NON-NLS-1$ Args.notNull(allowedCiphers, "Allowed ciphers"); //$NON-NLS-1$ TrustStrategy trustStrategy = trustSelfSigned ? SELF_SIGNED : null; HostnameVerifier hostnameVerifier = allowAnyHostname ? ALLOW_ANY : SSLConnectionSocketFactory.getDefaultHostnameVerifier(); PrivateKeyStrategy privateKeyStrategy = keyAliases == null ? null : new SelectByAlias(keyAliases); boolean clientAuth = keyStore == null ? false : true; SSLContextBuilder builder = SSLContexts.custom(); if (trustStore != null) { loadTrustMaterial(builder, new File(trustStore), trustStorePassword.toCharArray(), trustStrategy); } if (keyStore != null) { char[] ksp = keyStorePassword == null ? null : keyStorePassword.toCharArray(); char[] kp = keyPassword == null ? null : keyPassword.toCharArray(); loadKeyMaterial(builder, new File(keyStore), ksp, kp, privateKeyStrategy); } SSLContext sslContext = builder.build(); return new SSLSessionStrategy(hostnameVerifier, new CipherSelectingSSLSocketFactory( sslContext.getSocketFactory(), allowedCiphers, allowedProtocols, clientAuth)); }