Create a new  SSL engine, configured from an option map.

@param sslContext the SSL context
@param optionMap the SSL options
@param peerAddress the peer address of the connection
@return the configured SSL engine
354254
private static SSLEngine createSSLEngine(SSLContext sslContext, OptionMap optionMap, InetSocketAddress peerAddress, boolean client) {
        final SSLEngine engine = sslContext.createSSLEngine(
                optionMap.get(Options.SSL_PEER_HOST_NAME, peerAddress.getHostString()),
                optionMap.get(Options.SSL_PEER_PORT, peerAddress.getPort())
        );
        engine.setUseClientMode(client);
        engine.setEnableSessionCreation(optionMap.get(Options.SSL_ENABLE_SESSION_CREATION, true));
        final Sequence<String> cipherSuites = optionMap.get(Options.SSL_ENABLED_CIPHER_SUITES);
        if (cipherSuites != null) {
            final Set<String> supported = new HashSet<String>(Arrays.asList(engine.getSupportedCipherSuites()));
            final List<String> finalList = new ArrayList<String>();
            for (String name : cipherSuites) {
                if (supported.contains(name)) {
                    finalList.add(name);
                }
            }
            engine.setEnabledCipherSuites(finalList.toArray(new String[finalList.size()]));
        }
        final Sequence<String> protocols = optionMap.get(Options.SSL_ENABLED_PROTOCOLS);
        if (protocols != null) {
            final Set<String> supported = new HashSet<String>(Arrays.asList(engine.getSupportedProtocols()));
            final List<String> finalList = new ArrayList<String>();
            for (String name : protocols) {
                if (supported.contains(name)) {
                    finalList.add(name);
                }
            }
            engine.setEnabledProtocols(finalList.toArray(new String[finalList.size()]));
        }
        return engine;
    }
510142
@Override
    protected Future<SslContext> lookup(ChannelHandlerContext ctx, String hostname) throws Exception {
        return mapping.map(hostname, ctx.executor().<SslContext>newPromise());
    }
524720
public static WebsocketServerTransport create(String bindAddress, int port) {
    Objects.requireNonNull(bindAddress, "bindAddress must not be null");

    HttpServer httpServer = HttpServer.create().host(bindAddress).port(port);
    return create(httpServer);
  }
1316050
public static SSLServerSocketChannel open(SocketAddress address) throws IOException
    {
        try
        {
            return open(address, SSLContext.getDefault());
        }
        catch (NoSuchAlgorithmException ex)
        {
            throw new IOException(ex);
        }
    }
823368
protected void addSslHandler(ChannelPipeline pipeline) {
        if (sslContext != null) {
            SSLEngine engine = sslContext.createSSLEngine();
            engine.setUseClientMode(false);
            pipeline.addLast(SSL_HANDLER, new SslHandler(engine));
        }
    }
796984
public SSLEngine buildServerSSLEngine(SSLContext sslContext) {
        SSLEngine engine = sslContext.createSSLEngine();
        engine.setUseClientMode(false);
        if (needClientAuth) {
            engine.setNeedClientAuth(true);
        } else if (wantClientAuth) {
            engine.setWantClientAuth(true);
        }
        return addCommonConfigs(engine);
    }
790114
@Nullable
	private static SSLContext createRestSSLContext(Configuration config, RestSSLContextConfigMode configMode) throws Exception {
		checkNotNull(config, "config");

		if (!isRestSSLEnabled(config)) {
			return null;
		}

		KeyManager[] keyManagers = null;
		if (configMode == RestSSLContextConfigMode.SERVER || configMode == RestSSLContextConfigMode.MUTUAL) {
			String keystoreFilePath = getAndCheckOption(
				config, SecurityOptions.SSL_REST_KEYSTORE, SecurityOptions.SSL_KEYSTORE);

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

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

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

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

			keyManagers = kmf.getKeyManagers();
		}

		TrustManager[] trustManagers = null;
		if (configMode == RestSSLContextConfigMode.CLIENT || configMode == RestSSLContextConfigMode.MUTUAL) {
			String trustStoreFilePath = getAndCheckOption(
				config, SecurityOptions.SSL_REST_TRUSTSTORE, SecurityOptions.SSL_TRUSTSTORE);

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

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

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

			trustManagers = tmf.getTrustManagers();
		}

		String sslProtocolVersion = config.getString(SecurityOptions.SSL_PROTOCOL);
		SSLContext sslContext = SSLContext.getInstance(sslProtocolVersion);
		sslContext.init(keyManagers, trustManagers, null);

		return sslContext;
	}
679412
@Override
    public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.entry(tc, "chooseEngineServerAlias", new Object[] { keyType, issuers, engine });

        String rc = null;
        if (null != customKM && customKM instanceof X509ExtendedKeyManager) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "chooseEngineServerAlias, using customKM -> " + customKM.getClass().getName());
            rc = ((X509ExtendedKeyManager) customKM).chooseEngineServerAlias(keyType, issuers, engine);
        } else {
            rc = chooseServerAlias(keyType, issuers);
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            Tr.exit(tc, "chooseEngineServerAlias: " + rc);
        return rc;
    }
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);
    }
  }
1340549
@SuppressWarnings("deprecation")
    private final HttpResponse executeHttpRequest(HttpGet getMethod, String host) throws Exception {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
            new String[] { "TLSv1" },
            null,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Registry registry = RegistryBuilder.create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", sslsf)
            .build();
        HttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);
        CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setMaxConnPerRoute(50)
            .setMaxConnTotal(100)
            .setConnectionManager(httpClientConnectionManager)
            .build();
        RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout)
            .setSocketTimeout(timeout)
            .build();
        getMethod.setConfig(requestConfig);
        HttpResponse response = httpClient.execute(getMethod);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpResponseStatus.OK.code() && statusCode != HttpResponseStatus.PARTIAL_CONTENT.code()) {
            String result = EntityUtils.toString(response.getEntity());
            throw new RuntimeException("return error !" + response.getStatusLine().getReasonPhrase() + ", " + result);
        }
        return response;
    }
650189
public static void configureTls(ServerBuilder sb, Ssl ssl,
                                    @Nullable Supplier<KeyStore> keyStoreSupplier,
                                    @Nullable Supplier<KeyStore> trustStoreSupplier) {
        if (!ssl.isEnabled()) {
            return;
        }
        try {
            if (keyStoreSupplier == null && trustStoreSupplier == null &&
                ssl.getKeyStore() == null && ssl.getTrustStore() == null) {
                logger.warn("Configuring TLS with a self-signed certificate " +
                            "because no key or trust store was specified");
                sb.tlsSelfSigned();
                return;
            }

            final KeyManagerFactory keyManagerFactory = getKeyManagerFactory(ssl, keyStoreSupplier);
            final TrustManagerFactory trustManagerFactory = getTrustManagerFactory(ssl, trustStoreSupplier);

            sb.tls(keyManagerFactory, sslContextBuilder -> {
                sslContextBuilder.trustManager(trustManagerFactory);

                final SslProvider sslProvider = ssl.getProvider();
                if (sslProvider != null) {
                    sslContextBuilder.sslProvider(sslProvider);
                }
                final List<String> enabledProtocols = ssl.getEnabledProtocols();
                if (enabledProtocols != null) {
                    sslContextBuilder.protocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
                }
                final List<String> ciphers = ssl.getCiphers();
                if (ciphers != null) {
                    sslContextBuilder.ciphers(ImmutableList.copyOf(ciphers),
                                              SupportedCipherSuiteFilter.INSTANCE);
                }
                final ClientAuth clientAuth = ssl.getClientAuth();
                if (clientAuth != null) {
                    sslContextBuilder.clientAuth(clientAuth);
                }
            });
        } catch (Exception e) {
            throw new IllegalStateException("Failed to configure TLS: " + e, e);
        }
    }
659415
protected void registerIbmAlpn(SSLEngine engine, boolean useAlpn) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "registerIbmAlpn entry " + engine);
        }
        try {
            // invoke ALPNJSSEExt.put(engine, String[] protocols)
            String[] protocols;
            if (useAlpn) {
                protocols = new String[] { h2, h1 };
            } else {
                // don't pass any protocols; alpn not used
                protocols = new String[] {};
            }
            ibmAlpnPut.invoke(null, engine, protocols);

        } catch (InvocationTargetException ie) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "registerIbmAlpn exception: " + ie.getTargetException());
            }
        } catch (Exception e) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "registerIbmAlpn exception: " + e);
            }
        }
    }
611034
public static ClientHttpConnector create(ClientOptions options) {
		HttpClient httpClient = HttpClient.create();

		if (usingCustomCerts(options)) {
			TrustManagerFactory trustManagerFactory =
					sslCertificateUtils.createTrustManagerFactory(options.getCaCertFiles());

			httpClient = httpClient.secure(sslContextSpec -> sslContextSpec
					.sslContext(SslContextBuilder.forClient()
							.sslProvider(SslProvider.JDK)
							.trustManager(trustManagerFactory)));
		} else {
			httpClient = httpClient.secure(sslContextSpec -> sslContextSpec
					.sslContext(SslContextBuilder.forClient()
							.sslProvider(SslProvider.JDK)));
		}

		if (options.getConnectionTimeout() != null) {
			httpClient = httpClient.tcpConfiguration(tcpClient ->
					tcpClient.option(ChannelOption.CONNECT_TIMEOUT_MILLIS,
							Math.toIntExact(options.getConnectionTimeout().toMillis())));
		}

		return new ReactorClientHttpConnector(httpClient);
	}
203153
public SslContext createHttpTLSContextForClient() throws SSLException {
        SslProvider provider = SslProvider.JDK;
        SslContext certsSslContext = clientContextBuilderWithCerts(provider).build();
        int sessionTimeout = sslConfig.getSessionTimeOut();
        if (sessionTimeout > 0) {
            certsSslContext.sessionContext().setSessionTimeout(sessionTimeout);
        }
        return certsSslContext;
    }
608672
public static ProtocolNegotiator serverTls(final SslContext sslContext) {
    Preconditions.checkNotNull(sslContext, "sslContext");
    return new ProtocolNegotiator() {
      @Override
      public ChannelHandler newHandler(GrpcHttp2ConnectionHandler handler) {
        return new ServerTlsHandler(sslContext, handler);
      }

      @Override
      public void close() {}


      @Override
      public AsciiString scheme() {
        return Utils.HTTPS;
      }
    };
  }
369464
public static SSLSocketFactory getSslSocketFactory(Options options) throws SQLException {

    TrustManager[] trustManager = null;
    KeyManager[] keyManager = null;

    if (options.trustServerCertificate || options.serverSslCert != null
        || options.trustStore != null) {
      trustManager = new X509TrustManager[]{new MariaDbX509TrustManager(options)};
    }

    if (options.keyStore != null) {
      keyManager = new KeyManager[]{
          loadClientCerts(options.keyStore, options.keyStorePassword, options.keyPassword, options.keyStoreType)};
    } else {
      String keyStore = System.getProperty("javax.net.ssl.keyStore");
      String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");
      if (keyStore != null) {
        try {
          keyManager = new KeyManager[]{
              loadClientCerts(keyStore, keyStorePassword, keyStorePassword, options.keyStoreType)};
        } catch (SQLException queryException) {
          keyManager = null;
          logger.error("Error loading keymanager from system properties", queryException);
        }
      }
    }

    try {
      SSLContext sslContext = SSLContext.getInstance("TLS");
      sslContext.init(keyManager, trustManager, null);
      return sslContext.getSocketFactory();
    } catch (KeyManagementException keyManagementEx) {
      throw ExceptionMapper.connException("Could not initialize SSL context", keyManagementEx);
    } catch (NoSuchAlgorithmException noSuchAlgorithmEx) {
      throw ExceptionMapper
          .connException("SSLContext TLS Algorithm not unknown", noSuchAlgorithmEx);
    }
  }
249375
public static CloseableHttpClient createKeyMaterialHttpClient(KeyStore keystore,String keyPassword,String[] supportedProtocols,int timeout,int retryExecutionCount) {
		try {
			SSLContext sslContext = SSLContexts.custom().useSSL().loadKeyMaterial(keystore, keyPassword.toCharArray()).build();
			SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext,supportedProtocols,
	                null,SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
			SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build();
			return HttpClientBuilder.create()
									.setDefaultSocketConfig(socketConfig)
									.setSSLSocketFactory(sf)
									.setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount))
									.build();
		} catch (KeyManagementException e) {
			logger.error("", e);
		} catch (NoSuchAlgorithmException e) {
			logger.error("", e);
		} catch (UnrecoverableKeyException e) {
			logger.error("", e);
		} catch (KeyStoreException e) {
			logger.error("", e);
		}
		return null;
	}