List of usage examples for javax.net.ssl SSLContext getSocketFactory
public final SSLSocketFactory getSocketFactory()
From source file:be.fgov.kszbcss.rhq.websphere.connector.agent.ConnectorSubsystemComponent.java
public OperationResult invokeOperation(String name, Configuration parameters) throws InterruptedException, Exception { if (name.equals("importCertificateFromFile")) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream in = new FileInputStream(parameters.getSimple("file").getStringValue()); try {// w ww.j ava 2s. c om Iterator<? extends Certificate> it = cf.generateCertificates(in).iterator(); if (it.hasNext()) { TrustStoreManager.getInstance().addCertificate(parameters.getSimple("alias").getStringValue(), (X509Certificate) it.next()); } else { throw new Exception("No certificate found"); } } finally { in.close(); } return null; } else if (name.equals("retrieveCellCertificate")) { DeploymentManager dm = new DeploymentManager(null, new ConfigurationBasedProcessLocator(parameters)); String cell = dm.getCell(); ConfigQueryExecutor configQueryExecutor = ConfigQueryServiceFactory.getInstance() .getConfigQueryExecutor(dm); try { X509Certificate cert = configQueryExecutor.query(CellRootCertificateQuery.INSTANCE); TrustStoreManager.getInstance().addCertificate("cell:" + cell, cert); } finally { configQueryExecutor.destroy(); } return null; } else if (name.equals("retrieveCertificateFromPort")) { SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(new KeyManager[0], new TrustManager[] { new AutoImportTrustManager(parameters.getSimple("alias").getStringValue()) }, new SecureRandom()); SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket( parameters.getSimple("host").getStringValue(), parameters.getSimple("port").getIntegerValue()); try { socket.startHandshake(); } finally { socket.close(); } return null; } else if (name.equals("listCertificates")) { final PropertyList certificates = new PropertyList("certificates"); TrustStoreManager.getInstance().execute(new TrustStoreAction() { public void execute(KeyStore truststore) throws Exception { // Sort the aliases for convenience Set<String> aliases = new TreeSet<String>(); for (Enumeration<String> e = truststore.aliases(); e.hasMoreElements();) { aliases.add(e.nextElement()); } for (String alias : aliases) { X509Certificate cert = (X509Certificate) truststore.getCertificate(alias); PropertyMap map = new PropertyMap("certificate"); map.put(new PropertySimple("alias", alias)); map.put(new PropertySimple("subject", cert.getSubjectDN().toString())); MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(cert.getEncoded()); byte[] digest = md.digest(); StringBuilder fingerprint = new StringBuilder(); for (int i = 0; i < digest.length; i++) { if (i > 0) { fingerprint.append(':'); } fingerprint.append(getHexDigit(((int) digest[i] & 0xf0) >> 4)); fingerprint.append(getHexDigit((int) digest[i] & 0x0f)); } map.put(new PropertySimple("fingerprint", fingerprint.toString())); certificates.add(map); } } }, true); if (log.isDebugEnabled()) { log.debug("certificates=" + certificates); } OperationResult result = new OperationResult(); result.getComplexResults().put(certificates); return result; } else if (name.equals("removeCertificate")) { final String alias = parameters.getSimple("alias").getStringValue(); TrustStoreManager.getInstance().execute(new TrustStoreAction() { public void execute(KeyStore truststore) throws Exception { truststore.deleteEntry(alias); } }, false); return null; } else if (name.equals("renameCertificate")) { final String oldAlias = parameters.getSimple("oldAlias").getStringValue(); final String newAlias = parameters.getSimple("newAlias").getStringValue(); TrustStoreManager.getInstance().execute(new TrustStoreAction() { public void execute(KeyStore truststore) throws Exception { Certificate cert = truststore.getCertificate(oldAlias); truststore.setCertificateEntry(newAlias, cert); truststore.deleteEntry(oldAlias); } }, false); return null; } else { return null; } }
From source file:org.apache.nifi.lookup.RestLookupService.java
@OnEnabled public void onEnabled(final ConfigurationContext context) { readerFactory = context.getProperty(RECORD_READER).asControllerService(RecordReaderFactory.class); proxyConfigurationService = context.getProperty(PROXY_CONFIGURATION_SERVICE) .asControllerService(ProxyConfigurationService.class); OkHttpClient.Builder builder = new OkHttpClient.Builder(); setAuthenticator(builder, context);// w ww .j a v a 2 s . c o m if (proxyConfigurationService != null) { setProxy(builder); } final SSLContextService sslService = context.getProperty(SSL_CONTEXT_SERVICE) .asControllerService(SSLContextService.class); final SSLContext sslContext = sslService == null ? null : sslService.createSSLContext(SSLContextService.ClientAuth.WANT); if (sslService != null) { builder.sslSocketFactory(sslContext.getSocketFactory()); } client = builder.build(); String path = context.getProperty(RECORD_PATH).isSet() ? context.getProperty(RECORD_PATH).getValue() : null; if (!StringUtils.isBlank(path)) { recordPath = RecordPath.compile(path); } buildHeaders(context); urlTemplate = context.getProperty(URL); }
From source file:net.hiroq.rxwsc.RxWebSocketClient.java
/** * Init SSL/TSL context and get SocketFactory * * @return//from w ww . j a va2 s.c om * @throws NoSuchAlgorithmException * @throws KeyManagementException */ protected SSLSocketFactory getSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, sTrustManagers, null); return context.getSocketFactory(); }
From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java
private HttpsURLConnection openSecureConnection(URL url) throws Exception { InputStream keyStream = new FileInputStream(truststorePath); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(keyStream, Optional.ofNullable(truststorePassword).orElse("").toCharArray()); TrustManagerFactory trustFactory = TrustManagerFactory.getInstance( Optional.ofNullable(truststoreAlgorithm).orElseGet(TrustManagerFactory::getDefaultAlgorithm)); trustFactory.init(keystore);// w w w . ja va 2 s . c o m SSLContext context = SSLContext.getInstance("TLS"); context.init(null, trustFactory.getTrustManagers(), null); HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection(); httpsURLConnection.setSSLSocketFactory(context.getSocketFactory()); httpsURLConnection.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); return httpsURLConnection; }
From source file:org.ops4j.pax.web.service.jetty.internal.JettyFactoryImpl.java
/** * {@inheritDoc}// ww w . j a va 2 s . c o m */ @Override public ServerConnector createSecureConnector(Server server, String name, int port, String sslKeystore, String sslKeystorePassword, String sslKeyPassword, String host, String sslKeystoreType, String sslKeyAlias, String trustStore, String trustStorePassword, String trustStoreType, boolean isClientAuthNeeded, boolean isClientAuthWanted, List<String> cipherSuitesIncluded, List<String> cipherSuitesExcluded, List<String> protocolsIncluded, List<String> protocolsExcluded, Boolean sslRenegotiationAllowed, String crlPath, Boolean enableCRLDP, Boolean validateCerts, Boolean validatePeerCerts, Boolean enableOCSP, String ocspResponderURL) { // SSL Context Factory for HTTPS and SPDY SslContextFactory sslContextFactory = new SslContextFactory(); sslContextFactory.setKeyStorePath(sslKeystore); sslContextFactory.setKeyStorePassword(sslKeystorePassword); sslContextFactory.setKeyManagerPassword(sslKeyPassword); sslContextFactory.setNeedClientAuth(isClientAuthNeeded); sslContextFactory.setWantClientAuth(isClientAuthWanted); sslContextFactory.setEnableCRLDP(enableCRLDP); sslContextFactory.setValidateCerts(validateCerts); sslContextFactory.setValidatePeerCerts(validatePeerCerts); sslContextFactory.setEnableOCSP(enableOCSP); if ((null != crlPath) && (!"".equals(crlPath))) { sslContextFactory.setCrlPath(crlPath); } if ((null != ocspResponderURL) && (!"".equals(ocspResponderURL))) { sslContextFactory.setOcspResponderURL(ocspResponderURL); } if (sslKeystoreType != null) { sslContextFactory.setKeyStoreType(sslKeystoreType); } // Java key stores may contain more than one private key entry. // Specifying the alias tells jetty which one to use. if ((null != sslKeyAlias) && (!"".equals(sslKeyAlias))) { sslContextFactory.setCertAlias(sslKeyAlias); } // Quite often it is useful to use a certificate trust store other than the JVM default. if ((null != trustStore) && (!"".equals(trustStore))) { sslContextFactory.setTrustStorePath(trustStore); } if ((null != trustStorePassword) && (!"".equals(trustStorePassword))) { sslContextFactory.setTrustStorePassword(trustStorePassword); } if ((null != trustStoreType) && (!"".equals(trustStoreType))) { sslContextFactory.setTrustStoreType(trustStoreType); } // In light of well-known attacks against weak encryption algorithms such as RC4, // it is usefull to be able to include or exclude certain ciphersuites. // Due to the overwhelming number of cipher suites using regex to specify inclusions // and exclusions greatly simplifies configuration. final String[] cipherSuites; try { SSLContext context = SSLContext.getDefault(); SSLSocketFactory sf = context.getSocketFactory(); cipherSuites = sf.getSupportedCipherSuites(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Failed to get supported cipher suites.", e); } if (cipherSuitesIncluded != null && !cipherSuitesIncluded.isEmpty()) { final List<String> cipherSuitesToInclude = new ArrayList<>(); for (final String cipherSuite : cipherSuites) { for (final String includeRegex : cipherSuitesIncluded) { if (cipherSuite.matches(includeRegex)) { cipherSuitesToInclude.add(cipherSuite); } } } sslContextFactory.setIncludeCipherSuites( cipherSuitesToInclude.toArray(new String[cipherSuitesToInclude.size()])); } if (cipherSuitesExcluded != null && !cipherSuitesExcluded.isEmpty()) { final List<String> cipherSuitesToExclude = new ArrayList<>(); for (final String cipherSuite : cipherSuites) { for (final String excludeRegex : cipherSuitesExcluded) { if (cipherSuite.matches(excludeRegex)) { cipherSuitesToExclude.add(cipherSuite); } } } sslContextFactory.setExcludeCipherSuites( cipherSuitesToExclude.toArray(new String[cipherSuitesToExclude.size()])); } // In light of attacks against SSL 3.0 as "POODLE" it is useful to include or exclude // SSL/TLS protocols as needed. if ((null != protocolsIncluded) && (!protocolsIncluded.isEmpty())) { sslContextFactory.setIncludeProtocols(protocolsIncluded.toArray(new String[protocolsIncluded.size()])); } if ((null != protocolsExcluded) && (!protocolsExcluded.isEmpty())) { sslContextFactory.setExcludeProtocols(protocolsExcluded.toArray(new String[protocolsExcluded.size()])); } if (sslRenegotiationAllowed != null) { sslContextFactory.setRenegotiationAllowed(sslRenegotiationAllowed); } // HTTP Configuration HttpConfiguration httpConfig = new HttpConfiguration(); httpConfig.setSecureScheme(HttpScheme.HTTPS.asString()); httpConfig.setSecurePort(port); httpConfig.setOutputBufferSize(32768); // HTTPS Configuration HttpConfiguration httpsConfig = new HttpConfiguration(httpConfig); httpsConfig.addCustomizer(new SecureRequestCustomizer()); List<AbstractConnectionFactory> connectionFactories = new ArrayList<>(); HttpConnectionFactory httpConFactory = new HttpConnectionFactory(httpsConfig); SslConnectionFactory sslFactory = null; AbstractConnectionFactory http2Factory = null; NegotiatingServerConnectionFactory alpnFactory = null; if (alpnCLassesAvailable()) { log.info("HTTP/2 available, creating HttpSpdyServerConnector for Https"); // SPDY connector try { Class<?> comparatorClass = bundle.loadClass("org.eclipse.jetty.http2.HTTP2Cipher"); Comparator<String> cipherComparator = (Comparator<String>) FieldUtils .readDeclaredStaticField(comparatorClass, "COMPARATOR"); sslContextFactory.setCipherComparator(cipherComparator); sslFactory = new SslConnectionFactory(sslContextFactory, "h2"); connectionFactories.add(sslFactory); //org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory Class<?> loadClass = bundle .loadClass("org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory"); // // //ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory("spdy/3", "http/1.1"); // alpnFactory = (NegotiatingServerConnectionFactory) ConstructorUtils.invokeConstructor(loadClass, (Object) new String[] {"ssl", "http/2", "http/1.1"}); // alpnFactory.setDefaultProtocol("http/1.1"); // connectionFactories.add(alpnFactory); //HTTPSPDYServerConnectionFactory spdy = new HTTPSPDYServerConnectionFactory(SPDY.V3, httpConfig); // loadClass = bundle.loadClass("org.eclipse.jetty.spdy.server.http.HTTPSPDYServerConnectionFactory"); // loadClass = bundle.loadClass("org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory"); http2Factory = (AbstractConnectionFactory) ConstructorUtils.invokeConstructor(loadClass, httpsConfig); connectionFactories.add(http2Factory); } catch (ClassNotFoundException | NoSuchMethodException | InvocationTargetException | IllegalArgumentException | IllegalAccessException | InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { log.info("SPDY not available, creating standard ServerConnector for Https"); sslFactory = new SslConnectionFactory(sslContextFactory, "http/1.1"); } // HttpConnectionFactory httpFactory = new HttpConnectionFactory(httpConfig); // // ServerConnector https = new ServerConnector(server); // HTTPS connector ServerConnector https = new ServerConnector(server, sslFactory, httpConFactory); for (AbstractConnectionFactory factory : connectionFactories) { https.addConnectionFactory(factory); } https.setPort(port); https.setName(name); https.setHost(host); https.setIdleTimeout(500000); /* SslContextFactory sslContextFactory = new SslContextFactory(); HttpConfiguration httpConfig = new HttpConfiguration(); SslConnectionFactory ssl = new SslConnectionFactory(sslContextFactory, "alpn"); ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory("spdy/3", "http/1.1"); alpn.setDefaultProtocol("http/1.1"); HTTPSPDYServerConnectionFactory spdy = new HTTPSPDYServerConnectionFactory(SPDY.V3, httpConfig); HttpConnectionFactory http = new HttpConnectionFactory(httpConfig); Server server = new Server(); ServerConnector connector = new ServerConnector(server, new ConnectionFactory[]{ssl, alpn, spdy, http}); */ return https; }
From source file:com.openshift.internal.restclient.http.UrlConnectionHttpClient.java
private SSLContext setSSLCallback(ISSLCertificateCallback sslAuthorizationCallback, URL url, HttpsURLConnection connection) { X509TrustManager trustManager = null; if (sslAuthorizationCallback != null) { connection.setHostnameVerifier(new CallbackHostnameVerifier()); trustManager = createCallbackTrustManager(sslAuthorizationCallback, connection); }/*from ww w. j a v a 2 s. c o m*/ try { SSLContext sslContext = SSLUtils.getSSLContext(trustManager); connection.setSSLSocketFactory(sslContext.getSocketFactory()); return sslContext; } catch (GeneralSecurityException e) { LOGGER.warn("Could not install trust manager callback", e); ; return null; } }
From source file:org.codice.ddf.itests.common.cometd.CometDClient.java
private void doTrustAllCertificates() throws NoSuchAlgorithmException, KeyManagementException { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override/*from w ww . j a v a2 s . co m*/ public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); HostnameVerifier hostnameVerifier = (s, sslSession) -> s.equalsIgnoreCase(sslSession.getPeerHost()); HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); }
From source file:jp.pigumer.mqtt.Client.java
void createMqttConnectOptions() { Optional<SSLContext> context = initTrustManagers().map(trustManagers -> { try {//from www .ja v a 2s .c om SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, trustManagers, new SecureRandom()); return sslContext; } catch (Exception e) { LOGGER.log(Level.SEVERE, "failed load", e); return null; } }); options = new MqttConnectOptions(); options.setUserName(userName); options.setPassword(password); context.ifPresent(sslContext -> options.setSocketFactory(sslContext.getSocketFactory())); }
From source file:com.googlecode.onevre.utils.ServerClassLoader.java
private void addSslConnection(URLConnection connection) { if (connection instanceof HttpsURLConnection) { try {/* www . j a va 2 s. c o m*/ SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, new TrustManager[] { new AcceptAllTrustManager() }, new SecureRandom()); ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory()); ((HttpsURLConnection) connection).setHostnameVerifier(new AcceptAllHostnameVerifier()); } catch (Exception e) { e.printStackTrace(); } } }