/*
Configure the SSLContext to accept untrusted connections
358266
public static SSLContext getTlsSslContext() throws Exception {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            }
        }};
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init( null, trustAllCerts, new java.security.SecureRandom());
        return sslContext;
    }
120365
def localSslFixup(host, sslContext):
    
    if not sslContext and host in ['localhost', '127.0.0.1', '::1']:
        import ssl
        if hasattr(ssl, '_create_unverified_context'):
            sslContext = ssl._create_unverified_context()
    return sslContext
733459
private static SslHandler configureSslHandler(SslHandler sslHandler) {
        // Set endpoint identification algorithm so that JDK's default X509TrustManager implementation
        // performs host name checks. Without this, the X509TrustManager implementation will never raise
        // a CertificateException even if the domain name or IP address mismatches.
        final SSLEngine engine = sslHandler.engine();
        final SSLParameters params = engine.getSSLParameters();
        params.setEndpointIdentificationAlgorithm("HTTPS");
        engine.setSSLParameters(params);
        return sslHandler;
    }
473093
private static void configureEngine(SSLEngine engine, FlowType type, SSLLinkConfig config, SSLConnectionLink connLink) {
        // Update the engine with the latest config parameters.
        engine.setEnabledCipherSuites(config.getEnabledCipherSuites(engine));

        //Set the configured protocol on the SSLEngine
        String protocol = config.getSSLProtocol();
        if (protocol != null) {
            engine.setEnabledProtocols(new String[] { protocol });
        }

        if (type == FlowType.INBOUND) {
            engine.setUseClientMode(false);
            boolean flag = config.getBooleanProperty(Constants.SSLPROP_CLIENT_AUTHENTICATION);
            // When on z/OS, need to check the MutualAuthCBINDCheck property
            // to force client authentication
            //TODO: z/os
            //            if (PlatformHelperFactory.getPlatformHelper().isZOS() &&
            //            	 UserRegistryConfig.TYPE_LOCAL_OS.equals(SecurityObjectLocator.getSecurityConfig().getActiveUserRegistry().getType()))
            //            {
            //            	Boolean cbindCheckEnabled = Boolean.FALSE;
            //
            //            	//get the endpoint name off of the thread
            //                Map connectionInfo = JSSEHelper.getInstance().getInboundConnectionInfo();
            //                if (connectionInfo != null) {
            //                    String endpointName = (String) connectionInfo.get(Constants.CONNECTION_INFO_ENDPOINT_NAME);
            //                    //only enforce cbind check on web requests
            //                    if (endpointName != null && endpointName.startsWith("HTTP")) {
            //                    	if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            //                            Tr.debug(tc, "The endpoint, " + endpointName + ", is web and we are on z/OS. Proceeding to get the mutualAuthCbindCheck property.");
            //                        }
            //		                try {
            //		                    // Get cbind check flag using reflection
            //		                    final String className = "com.ibm.ws.security.zOS.NativeConfiguration";
            //		                    final Class<?> zNativeConfigClass = Class.forName(className);
            //		                    final Method getConfigMethod = zNativeConfigClass.getMethod("getConfig", (java.lang.Class[]) null);
            //		                    final Object configInstance = getConfigMethod.invoke((java.lang.Class[]) null, (java.lang.Object[]) null);
            //		                    final Method cbindCheckMethod = zNativeConfigClass.getMethod("isMutualAuthCBINDCheckEnabled", (java.lang.Class[]) null);
            //		                    cbindCheckEnabled = (Boolean) cbindCheckMethod.invoke(configInstance, (java.lang.Object[]) null);
            //		                } catch (Exception e) {
            //		                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            //		                        Tr.debug(tc, "No class, object, or method found for CBIND check", new Object[] {e});
            //		                    FFDCFilter.processException(e, CLASS_NAME, "1237");
            //		                }
            //		                if (cbindCheckEnabled.booleanValue()) {
            //		                    flag = cbindCheckEnabled.booleanValue();
            //		                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            //		                        Tr.debug(tc, "The mutualAuthCBINDCheck is true, so hard-coded setNeedClientAuth to true.");}
            //		                }
            //		            }
            //                }
            //            }

            engine.setNeedClientAuth(flag);
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Client auth needed is " + engine.getNeedClientAuth());
            }
            if (!flag) {
                // Client auth set to false, check client auth supported
                flag = config.getBooleanProperty(Constants.SSLPROP_CLIENT_AUTHENTICATION_SUPPORTED);
                engine.setWantClientAuth(flag);
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Client auth supported is " + engine.getWantClientAuth());
                }
            }
            // enable ALPN support if this is for an inbound connection
            AlpnSupportUtils.registerAlpnSupport(connLink, engine);

        } else {
            // Update engine with client side specific config parameters.
            engine.setUseClientMode(true);
        }

        try {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Calling beginHandshake on engine");
            }
            engine.beginHandshake();
        } catch (SSLException se) {
            // no FFDC required
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "Error while starting handshake; " + se);
            }
        }
    }
1153701
private SSLSocketFactory initSslSocketFactory(KeyManager[] kms, TrustManager[] tms)
			throws InitializationException {

		SSLContext ctx = null;

		String verify = System.getProperty(VERIFY_PEER_CERT_PROPERTY);


		// If VERIFY_PEER_PROPERTY is set to false, we don't want verification
		// of the other sides certificate
		if (verify != null &&  verify.equals("false")) {
			tms = getTrustAllKeystore();
		} else if (verify == null || verify != null && verify.equals("true")) {
			// use the given tms
		} else {
			throw new InitializationException("Bad value for "
					+ VERIFY_PEER_CERT_PROPERTY +  " property. Expected: true|false");
		}

		if (!isBasicAuth() && kms == null) {
			throw new InitializationException("certificate-based auth needs a KeyManager");
		}


		try {
			ctx = SSLContext.getInstance("TLS");
			ctx.init(kms, tms, new SecureRandom());
		} catch (Exception e) {
			/* catch all */
			IfmapJLog.error("Could not initialize SSLSocketFactory ["
								  + e.getMessage() + "]");
			throw new InitializationException(e);
		}
		return ctx.getSocketFactory();
	}
1189135
@Nullable
	private static SSLContext createInternalSSLContext(Configuration config) throws Exception {
		checkNotNull(config, "config");

		if (!isInternalSSLEnabled(config)) {
			return null;
		}
		String keystoreFilePath = getAndCheckOption(
				config, SecurityOptions.SSL_INTERNAL_KEYSTORE, SecurityOptions.SSL_KEYSTORE);

		String keystorePassword = getAndCheckOption(
				config, SecurityOptions.SSL_INTERNAL_KEYSTORE_PASSWORD, SecurityOptions.SSL_KEYSTORE_PASSWORD);

		String certPassword = getAndCheckOption(
				config, SecurityOptions.SSL_INTERNAL_KEY_PASSWORD, SecurityOptions.SSL_KEY_PASSWORD);

		String trustStoreFilePath = getAndCheckOption(
				config, SecurityOptions.SSL_INTERNAL_TRUSTSTORE, SecurityOptions.SSL_TRUSTSTORE);

		String trustStorePassword = getAndCheckOption(
				config, SecurityOptions.SSL_INTERNAL_TRUSTSTORE_PASSWORD, SecurityOptions.SSL_TRUSTSTORE_PASSWORD);

		String sslProtocolVersion = config.getString(SecurityOptions.SSL_PROTOCOL);
		int sessionCacheSize = config.getInteger(SecurityOptions.SSL_INTERNAL_SESSION_CACHE_SIZE);
		int sessionTimeoutMs = config.getInteger(SecurityOptions.SSL_INTERNAL_SESSION_TIMEOUT);

		KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
		try (InputStream keyStoreFile = Files.newInputStream(new File(keystoreFilePath).toPath())) {
			keyStore.load(keyStoreFile, keystorePassword.toCharArray());
		}

		KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
		try (InputStream trustStoreFile = Files.newInputStream(new File(trustStoreFilePath).toPath())) {
			trustStore.load(trustStoreFile, trustStorePassword.toCharArray());
		}

		KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		kmf.init(keyStore, certPassword.toCharArray());

		TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		tmf.init(trustStore);

		SSLContext sslContext = SSLContext.getInstance(sslProtocolVersion);
		sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
		if (sessionCacheSize >= 0) {
			sslContext.getClientSessionContext().setSessionCacheSize(sessionCacheSize);
		}
		if (sessionTimeoutMs >= 0) {
			sslContext.getClientSessionContext().setSessionTimeout(sessionTimeoutMs / 1000);
		}

		return sslContext;
	}
826375
private SSLConfig parseSecureSocketLayer(Map<String, Object> map, boolean reinitialize) throws Exception {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "parseSecureSocketLayer");

        SSLConfig sslprops = new SSLConfig();

        // READ KEYSTORE OBJECT(S)
        WSKeyStore wsks_key = null;
        String keyStoreName = (String) map.get(LibertyConstants.KEY_KEYSTORE_REF);
        if (null != keyStoreName) {
            wsks_key = KeyStoreManager.getInstance().getKeyStore(keyStoreName);
        }

        if (wsks_key != null) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "Adding keystore properties from KeyStore object.");
            sslprops.setProperty(Constants.SSLPROP_KEY_STORE_NAME, keyStoreName);
            addSSLPropertiesFromKeyStore(wsks_key, sslprops);
        }

        String trustStoreName = (String) map.get(LibertyConstants.KEY_TRUSTSTORE_REF);
        WSKeyStore wsks_trust = null;
        if (null != trustStoreName) {
            wsks_trust = KeyStoreManager.getInstance().getKeyStore(trustStoreName);
        } else {
            trustStoreName = (String) map.get(LibertyConstants.KEY_KEYSTORE_REF);
            wsks_trust = wsks_key;
        }

        if (wsks_trust != null) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "Adding truststore properties from KeyStore object.");
            sslprops.setProperty(Constants.SSLPROP_TRUST_STORE_NAME, trustStoreName);
            addSSLPropertiesFromTrustStore(wsks_trust, sslprops);
        }

        // KEY MANAGER
        String defaultkeyManager = JSSEProviderFactory.getKeyManagerFactoryAlgorithm();
        if (defaultkeyManager != null) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "Setting default KeyManager: " + defaultkeyManager);
            sslprops.setProperty(Constants.SSLPROP_KEY_MANAGER, defaultkeyManager);
        }

        // TRUST MANAGERS
        String defaultTrustManager = JSSEProviderFactory.getTrustManagerFactoryAlgorithm();

        if (defaultTrustManager != null) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "Setting default TrustManager: " + defaultTrustManager);
            sslprops.setProperty(Constants.SSLPROP_TRUST_MANAGER, defaultTrustManager);
        }

        // MISCELLANEOUS ATTRIBUTES
        String sslProtocol = (String) map.get("sslProtocol");
        if (sslProtocol != null && !sslProtocol.isEmpty())
            sslprops.setProperty(Constants.SSLPROP_PROTOCOL, sslProtocol);

        String contextProvider = (String) map.get("jsseProvider");
        if (contextProvider != null && !contextProvider.isEmpty()) {
            // setting IBMJSSE2 since IBMJSSE and IBMJSSEFIPS is not supported any
            // longer
            if (contextProvider.equalsIgnoreCase(Constants.IBMJSSE_NAME) || contextProvider.equalsIgnoreCase(Constants.IBMJSSEFIPS_NAME)) {
                contextProvider = Constants.IBMJSSE2_NAME;
            }

            sslprops.setProperty(Constants.SSLPROP_CONTEXT_PROVIDER, contextProvider);
        }

        Boolean clientAuth = (Boolean) map.get("clientAuthentication");
        if (null != clientAuth) {
            sslprops.setProperty(Constants.SSLPROP_CLIENT_AUTHENTICATION, clientAuth.toString());
        }

        Boolean clientAuthSup = (Boolean) map.get("clientAuthenticationSupported");
        if (null != clientAuthSup) {
            sslprops.setProperty(Constants.SSLPROP_CLIENT_AUTHENTICATION_SUPPORTED, clientAuthSup.toString());
        }

        String prop = (String) map.get("securityLevel");
        if (null != prop && !prop.isEmpty()) {
            sslprops.setProperty(Constants.SSLPROP_SECURITY_LEVEL, prop);
        }

        prop = (String) map.get("clientKeyAlias");
        if (null != prop && !prop.isEmpty()) {
            sslprops.setProperty(Constants.SSLPROP_KEY_STORE_CLIENT_ALIAS, prop);
        }

        prop = (String) map.get("serverKeyAlias");
        if (null != prop && !prop.isEmpty()) {
            sslprops.setProperty(Constants.SSLPROP_KEY_STORE_SERVER_ALIAS, prop);
        }

        prop = (String) map.get("enabledCiphers");
        if (null != prop && !prop.isEmpty()) {
            sslprops.setProperty(Constants.SSLPROP_ENABLED_CIPHERS, prop);
        }

        prop = (String) map.get("id");
        if (null != prop && !prop.isEmpty()) {
            sslprops.setProperty(Constants.SSLPROP_ALIAS, prop);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, "Saving SSLConfig: " + sslprops);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "parseSecureSocketLayer");
        return sslprops;
    }
1011954
public static InternalProtocolNegotiator.ProtocolNegotiator tls(SslContext sslContext) {
    final io.grpc.netty.ProtocolNegotiator negotiator = ProtocolNegotiators.tls(sslContext);
    final class TlsNegotiator implements InternalProtocolNegotiator.ProtocolNegotiator {

      @Override
      public AsciiString scheme() {
        return negotiator.scheme();
      }

      @Override
      public ChannelHandler newHandler(GrpcHttp2ConnectionHandler grpcHandler) {
        return negotiator.newHandler(grpcHandler);
      }

      @Override
      public void close() {
        negotiator.close();
      }
    }
    
    return new TlsNegotiator();
  }
1334120
private void initializeHTTPClient() {

    if (_config.isHTTPSConfigured()) {
      try {
        KeyStore trustKeystore = getClientTruststore();
        SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(trustKeystore, new TrustSelfSignedStrategy())
            .build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        // Allow both HTTP and HTTPS connections
        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory> create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", sslsf)
            .build();

        HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);

        httpClient = HttpClients.custom()
            .setConnectionManager(cm)
            .build();

      } catch (Exception e) {
        LOGGER.error( "Issue creating HTTP client using supplied configuration. Proceeding with default non-SSL client.", e);
        httpClient = HttpClients.createDefault();
      }
    } else {

      httpClient = HttpClients.createDefault();
    }
  }
1191523
public static ApacheHttpTransport newTrustedTransport() throws GeneralSecurityException,
      IOException {
    // Set socket buffer sizes to 8192
    SocketConfig socketConfig =
        SocketConfig.custom()
            .setRcvBufSize(8192)
            .setSndBufSize(8192)
            .build();

    PoolingHttpClientConnectionManager connectionManager =
        new PoolingHttpClientConnectionManager(-1, TimeUnit.MILLISECONDS);

    // Disable the stale connection check (previously configured in the HttpConnectionParams
    connectionManager.setValidateAfterInactivity(-1);

    // Use the included trust store
    KeyStore trustStore = GoogleUtils.getCertificateTrustStore();
    SSLContext sslContext = SslUtils.getTlsSslContext();
    SslUtils.initSslContext(sslContext, trustStore, SslUtils.getPkixTrustManagerFactory());
    LayeredConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);

    HttpClient client = HttpClientBuilder.create()
        .useSystemProperties()
        .setSSLSocketFactory(socketFactory)
        .setDefaultSocketConfig(socketConfig)
        .setMaxConnTotal(200)
        .setMaxConnPerRoute(20)
        .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
        .setConnectionManager(connectionManager)
        .disableRedirectHandling()
        .disableAutomaticRetries()
        .build();
    return new ApacheHttpTransport(client);
  }
1004412
public void setEnabledCipherSuites(String[] suites) throws SSLException {
        if (this.isOutbound) {
            this.sslConnLink.getSSLEngine().setEnabledCipherSuites(suites);
        } else {
            throw new SocketEstablishedSSLException("Error, established setting cannot be modified.");
        }
    }
454006
private void configureSsl(SocketChannel ch) {
        SslContext sslCtx = SslContextBuilder.build();
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
        // We must wait for the handshake to finish and the protocol to be negotiated before configuring
        // the HTTP/2 components of the pipeline.
        pipeline.addLast(new ApplicationProtocolNegotiationHandler("") {
            @Override
            protected void configurePipeline(ChannelHandlerContext ctx, String protocol) {
                if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                    ChannelPipeline p = ctx.pipeline();
                    p.addLast(connectionHandler);
                    configureEndOfPipeline(p);
                    return;
                }
                ctx.close();
                throw new IllegalStateException("unknown protocol: " + protocol);
            }
        });
    }
124094
def accept(self):
        """"""
        newsock, addr = socket.accept(self)
        ssl_sock = SSLSocket(newsock._sock,
                             keyfile=self.keyfile,
                             certfile=self.certfile,
                             server_side=True,
                             cert_reqs=self.cert_reqs,
                             ssl_version=self.ssl_version,
                             ca_certs=self.ca_certs,
                             do_handshake_on_connect=self.do_handshake_on_connect,
                             suppress_ragged_eofs=self.suppress_ragged_eofs,
                             ciphers=self.ciphers)
        return ssl_sock, addr
347641
protected synchronized void decorateWithTLS(TLSClientParameters tlsClientParameters,
                                                HttpURLConnection connection) throws GeneralSecurityException {

        int hash = tlsClientParameters.hashCode();
        if (hash != lastTlsHash) {
            lastTlsHash = hash;
            socketFactory = null;
        }

        // always reload socketFactory from HttpsURLConnection.defaultSSLSocketFactory and
        // tlsClientParameters.sslSocketFactory to allow runtime configuration change
        if (tlsClientParameters.isUseHttpsURLConnectionDefaultSslSocketFactory()) {
            socketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();

        } else if (tlsClientParameters.getSSLSocketFactory() != null) {
            // see if an SSLSocketFactory was set. This allows easy interop
            // with not-yet-commons-ssl.jar, or even just people who like doing their
            // own JSSE.
            socketFactory = tlsClientParameters.getSSLSocketFactory();

        } else if (socketFactory == null) {
            // ssl socket factory not yet instantiated, create a new one with tlsClientParameters's Trust
            // Managers, Key Managers, etc

            SSLContext ctx = org.apache.cxf.transport.https.SSLUtils.getSSLContext(tlsClientParameters);

            String[] cipherSuites = SSLUtils.getCiphersuitesToInclude(tlsClientParameters.getCipherSuites(),
                                                                      tlsClientParameters.getCipherSuitesFilter(),
                                                                      ctx.getSocketFactory().getDefaultCipherSuites(),
                                                                      SSLUtils.getSupportedCipherSuites(ctx),
                                                                      LOG);
            // The SSLSocketFactoryWrapper enables certain cipher suites
            // from the policy.
            String protocol = tlsClientParameters.getSecureSocketProtocol() != null ? tlsClientParameters.getSecureSocketProtocol() : "TLS";
            socketFactory = new SSLSocketFactoryWrapper(ctx.getSocketFactory(), cipherSuites, protocol);
            //recalc the hashcode since some of the above MAY have changed the tlsClientParameters
            lastTlsHash = tlsClientParameters.hashCode();
        } else {
            // ssl socket factory already initialized, reuse it to benefit of keep alive
        }

        HostnameVerifier verifier = org.apache.cxf.transport.https.SSLUtils.getHostnameVerifier(tlsClientParameters);

        if (connection instanceof HttpsURLConnection) {
            // handle the expected case (javax.net.ssl)
            final HttpsURLConnection conn = (HttpsURLConnection) connection;
            conn.setHostnameVerifier(verifier);
            AccessController.doPrivileged(new PrivilegedAction<Void>() {

                @Override
                public Void run() {
                    conn.setSSLSocketFactory(socketFactory);
                    return null;
                }
            });
        } else {
            // handle the deprecated sun case and other possible hidden API's
            // that are similar to the Sun cases
            try {
                Method method = connection.getClass().getMethod("getHostnameVerifier");

                InvocationHandler handler = new ReflectionInvokationHandler(verifier) {
                    @Override
                    public Object invoke(Object proxy,
                                         Method method,
                                         Object[] args) throws Throwable {
                        try {
                            return super.invoke(proxy, method, args);
                        } catch (Exception ex) {
                            return false;
                        }
                    }
                };
                Object proxy = java.lang.reflect.Proxy.newProxyInstance(this.getClass().getClassLoader(),
                                                                        new Class[] { method.getReturnType() },
                                                                        handler);

                method = connection.getClass().getMethod("setHostnameVerifier", method.getReturnType());
                method.invoke(connection, proxy);
            } catch (Exception ex) {
                //Ignore this one
            }
            try {
                Method getSSLSocketFactory = connection.getClass().getMethod("getSSLSocketFactory");
                Method setSSLSocketFactory = connection.getClass().getMethod("setSSLSocketFactory", getSSLSocketFactory.getReturnType());
                if (getSSLSocketFactory.getReturnType().isInstance(socketFactory)) {
                    setSSLSocketFactory.invoke(connection, socketFactory);
                } else {
                    //need to see if we can create one - mostly the weblogic case.   The
                    //weblogic SSLSocketFactory has a protected constructor that can take
                    //a JSSE SSLSocketFactory so we'll try and use that
                    Constructor<?> c = getSSLSocketFactory.getReturnType().getDeclaredConstructor(SSLSocketFactory.class);
                    ReflectionUtil.setAccessible(c);
                    setSSLSocketFactory.invoke(connection, c.newInstance(socketFactory));
                }
            } catch (Exception ex) {
                if (connection.getClass().getName().contains("weblogic")) {
                    if (!weblogicWarned) {
                        weblogicWarned = true;
                        LOG.warning("Could not configure SSLSocketFactory on Weblogic.  "
                                    + " Use the Weblogic control panel to configure the SSL settings.");
                    }
                    return;
                }
                //if we cannot set the SSLSocketFactor, we're in serious trouble.
                throw new IllegalArgumentException("Error decorating connection class "
                                                   + connection.getClass().getName(), ex);
            }
        }
    }
389669
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1784")
  @CanIgnoreReturnValue
  public static SslContextBuilder configure(SslContextBuilder builder, SslProvider provider) {
    switch (provider) {
      case JDK:
      {
        Provider jdkProvider = findJdkProvider();
        if (jdkProvider == null) {
          throw new IllegalArgumentException(
              "Could not find Jetty NPN/ALPN or Conscrypt as installed JDK providers");
        }
        return configure(builder, jdkProvider);
      }
      case OPENSSL:
      {
        ApplicationProtocolConfig apc;
        if (OpenSsl.isAlpnSupported()) {
          apc = NPN_AND_ALPN;
        } else {
          apc = NPN;
        }
        return builder
            .sslProvider(SslProvider.OPENSSL)
            .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
            .applicationProtocolConfig(apc);
      }
      default:
        throw new IllegalArgumentException("Unsupported provider: " + provider);
    }
  }
1211947
private void connect() throws IOException, GeneralSecurityException {
        synchronized (closedSync) {
            if (socket == null || socket.isClosed()) {
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, new TrustManager[] { new X509TrustAllManager() }, new SecureRandom());
                socket = sc.getSocketFactory().createSocket();
                socket.connect(address);
            }
            /**
             * Authenticate
             */
            CastChannel.DeviceAuthMessage authMessage = CastChannel.DeviceAuthMessage.newBuilder()
                    .setChallenge(CastChannel.AuthChallenge.newBuilder().build())
                    .build();

            CastChannel.CastMessage msg = CastChannel.CastMessage.newBuilder()
                    .setDestinationId(DEFAULT_RECEIVER_ID)
                    .setNamespace("urn:x-cast:com.google.cast.tp.deviceauth")
                    .setPayloadType(CastChannel.CastMessage.PayloadType.BINARY)
                    .setProtocolVersion(CastChannel.CastMessage.ProtocolVersion.CASTV2_1_0)
                    .setSourceId(name)
                    .setPayloadBinary(authMessage.toByteString())
                    .build();

            write(msg);
            CastChannel.CastMessage response = read();
            CastChannel.DeviceAuthMessage authResponse = CastChannel.DeviceAuthMessage.parseFrom(response.getPayloadBinary());
            if (authResponse.hasError()) {
                throw new ChromeCastException("Authentication failed: " + authResponse.getError().getErrorType().toString());
            }

            /**
             * Send 'PING' message
             */
            PingThread pingThread = new PingThread();
            pingThread.run();

            /**
             * Send 'CONNECT' message to start session
             */
            write("urn:x-cast:com.google.cast.tp.connection", StandardMessage.connect(), DEFAULT_RECEIVER_ID);

            /**
             * Start ping/pong and reader thread
             */
            pingTimer = new Timer(name + " PING");
            pingTimer.schedule(pingThread, 1000, PING_PERIOD);

            reader = new ReadThread();
            reader.start();

            if (closed) {
                closed = false;
                notifyListenerOfConnectionEvent(true);
            }
        }
    }
1190378
private SSLContext getSSLContext(String truststorePath,
                                     String truststorePassword,
                                     String keystorePath, 
                                     String keystorePassword) throws Exception {

        FileInputStream tsf = new FileInputStream(truststorePath);
        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(tsf, truststorePassword.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ts);

        FileInputStream ksf = new FileInputStream(keystorePath);
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(ksf, keystorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keystorePassword.toCharArray());

        SSLContext ctx = SSLContext.getInstance("SSL");
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
        return ctx;
    }