Java Code Examples for io.netty.handler.ssl.SslContextBuilder#trustManager()

The following examples show how to use io.netty.handler.ssl.SslContextBuilder#trustManager() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SecurityContextBuilder.java    From etcd4j with Apache License 2.0 6 votes vote down vote up
/**
 * Builds SslContext using protected keystore and truststores, overriding default key manger algorithm. Adequate for mutual TLS connections.
 * @param keystore Keystore inputstream (file, binaries, etc)
 * @param keystorePassword Password for protected keystore file
 * @param truststore Truststore inputstream (file, binaries, etc)
 * @param truststorePassword Password for protected truststore file
 * @param keyManagerAlgorithm Algorithm for keyManager used to process keystorefile
 * @return SslContext ready to use
 * @throws SecurityContextException
 */
public static SslContext forKeystoreAndTruststore(InputStream keystore, String keystorePassword, InputStream truststore, String truststorePassword, String keyManagerAlgorithm)
        throws SecurityContextException {
    try {
        final KeyStore ks = KeyStore.getInstance(KEYSTORE_JKS);
        final KeyStore ts = KeyStore.getInstance(KEYSTORE_JKS);

        final KeyManagerFactory keystoreKmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
        final TrustManagerFactory truststoreKmf = TrustManagerFactory.getInstance(keyManagerAlgorithm);

        ks.load(keystore, keystorePassword.toCharArray());
        ts.load(truststore, truststorePassword.toCharArray());

        keystoreKmf.init(ks, keystorePassword.toCharArray());
        truststoreKmf.init(ts);

        SslContextBuilder ctxBuilder = SslContextBuilder.forClient().keyManager(keystoreKmf);
        ctxBuilder.trustManager(truststoreKmf);

        return ctxBuilder.build();
    } catch (Exception e) {
        throw new SecurityContextException(e);
    }
}
 
Example 2
Source File: SslUtil.java    From Dream-Catcher with MIT License 6 votes vote down vote up
/**
 * Creates a netty SslContext for use when connecting to upstream servers. Retrieves the list of trusted root CAs
 * from the trustSource. When trustSource is true, no upstream certificate verification will be performed.
 * <b>This will make it possible for attackers to MITM communications with the upstream server</b>, so always
 * supply an appropriate trustSource except in extraordinary circumstances (e.g. testing with dynamically-generated
 * certificates).
 *
 * @param cipherSuites    cipher suites to allow when connecting to the upstream server
 * @param trustSource     the trust store that will be used to validate upstream servers' certificates, or null to accept all upstream server certificates
 * @return an SSLContext to connect to upstream servers with
 */
public static SslContext getUpstreamServerSslContext(Collection<String> cipherSuites, TrustSource trustSource) {
    SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

    if (trustSource == null) {
        log.warn("Disabling upstream server certificate verification. This will allow attackers to intercept communications with upstream servers.");

        sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslContextBuilder.trustManager(trustSource.getTrustedCAs());
    }

    sslContextBuilder.ciphers(cipherSuites, SupportedCipherSuiteFilter.INSTANCE);

    try {
        return sslContextBuilder.build();
    } catch (SSLException e) {
        throw new SslContextInitializationException("Error creating new SSL context for connection to upstream server", e);
    }
}
 
Example 3
Source File: SslSimpleBuilder.java    From jlogstash-input-plugin with Apache License 2.0 6 votes vote down vote up
public SslHandler build(ByteBufAllocator bufferAllocator) throws SSLException {
    SslContextBuilder builder = SslContextBuilder.forServer(sslCertificateFile, sslKeyFile, passPhrase);

    builder.ciphers(Arrays.asList(ciphers));

    if(requireClientAuth()) {
        logger.debug("Certificate Authorities: " + certificateAuthorities);
        builder.trustManager(new File(certificateAuthorities));
    }

    SslContext context = builder.build();
    SslHandler sslHandler = context.newHandler(bufferAllocator);

    SSLEngine engine = sslHandler.engine();
    engine.setEnabledProtocols(protocols);


    if(requireClientAuth()) {
        engine.setUseClientMode(false);
        engine.setNeedClientAuth(true);
    }

    return sslHandler;
}
 
Example 4
Source File: HelloWorldClientTls.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
private static SslContext buildSslContext(String trustCertCollectionFilePath,
                                          String clientCertChainFilePath,
                                          String clientPrivateKeyFilePath) throws SSLException {
    SslContextBuilder builder = GrpcSslContexts.forClient();
    if (trustCertCollectionFilePath != null) {
        builder.trustManager(new File(trustCertCollectionFilePath));
    }
    if (clientCertChainFilePath != null && clientPrivateKeyFilePath != null) {
        builder.keyManager(new File(clientCertChainFilePath), new File(clientPrivateKeyFilePath));
    }
    return builder.build();
}
 
Example 5
Source File: ClientHttpConnectorFactory.java    From spring-vault with Apache License 2.0 6 votes vote down vote up
private static void configureSsl(SslConfiguration sslConfiguration, SslContextBuilder sslContextBuilder) {

		try {

			if (sslConfiguration.getTrustStoreConfiguration().isPresent()) {
				sslContextBuilder
						.trustManager(createTrustManagerFactory(sslConfiguration.getTrustStoreConfiguration()));
			}

			if (sslConfiguration.getKeyStoreConfiguration().isPresent()) {
				sslContextBuilder.keyManager(createKeyManagerFactory(sslConfiguration.getKeyStoreConfiguration(),
						sslConfiguration.getKeyConfiguration()));
			}
		}
		catch (GeneralSecurityException | IOException e) {
			throw new IllegalStateException(e);
		}
	}
 
Example 6
Source File: TlsUtil.java    From nitmproxy with MIT License 5 votes vote down vote up
public static SslContext ctxForClient(NitmProxyConfig config) throws SSLException {
    SslContextBuilder builder = SslContextBuilder
            .forClient()
            .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
            .applicationProtocolConfig(applicationProtocolConfig(config, config.isServerHttp2()));
    if (config.isInsecure()) {
        builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    }
    return builder.build();
}
 
Example 7
Source File: ConnectionPoolImpl.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Obtain {@link SslContext} based on {@link ClientConfig}.
 */
@VisibleForTesting
SslContext getSslContext() {
    final SslContext sslCtx;
    if (clientConfig.isEnableTlsToSegmentStore()) {
        log.debug("Setting up an SSL/TLS Context");
        try {
            SslContextBuilder clientSslCtxBuilder = SslContextBuilder.forClient();

            if (Strings.isNullOrEmpty(clientConfig.getTrustStore())) {
                log.debug("Client truststore wasn't specified.");
                File clientTruststore = null; // variable for disambiguating method call
                clientSslCtxBuilder.trustManager(clientTruststore);
            } else {
                clientSslCtxBuilder.trustManager(new File(clientConfig.getTrustStore()));
                log.debug("Client truststore: {}", clientConfig.getTrustStore());
            }

            sslCtx = clientSslCtxBuilder.build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslCtx = null;
    }
    return sslCtx;
}
 
Example 8
Source File: GrafanaAuth.java    From timely with Apache License 2.0 5 votes vote down vote up
protected SslContext createSSLContext(GrafanaAuthConfiguration config) throws Exception {

        ServerSsl sslCfg = config.getSecurity().getServerSsl();
        Boolean generate = sslCfg.isUseGeneratedKeypair();
        SslContextBuilder ssl;
        if (generate) {
            LOG.warn("Using generated self signed server certificate");
            Date begin = new Date();
            Date end = new Date(begin.getTime() + 86400000);
            SelfSignedCertificate ssc = new SelfSignedCertificate("localhost", begin, end);
            ssl = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey());
        } else {
            String cert = sslCfg.getCertificateFile();
            String key = sslCfg.getKeyFile();
            String keyPass = sslCfg.getKeyPassword();
            if (null == cert || null == key) {
                throw new IllegalArgumentException("Check your SSL properties, something is wrong.");
            }
            ssl = SslContextBuilder.forServer(new File(cert), new File(key), keyPass);
        }

        ssl.ciphers(sslCfg.getUseCiphers());

        // Can't set to REQUIRE because the CORS pre-flight requests will fail.
        ssl.clientAuth(ClientAuth.OPTIONAL);

        Boolean useOpenSSL = sslCfg.isUseOpenssl();
        if (useOpenSSL) {
            ssl.sslProvider(SslProvider.OPENSSL);
        } else {
            ssl.sslProvider(SslProvider.JDK);
        }
        String trustStore = sslCfg.getTrustStoreFile();
        if (null != trustStore) {
            if (!trustStore.isEmpty()) {
                ssl.trustManager(new File(trustStore));
            }
        }
        return ssl.build();
    }
 
Example 9
Source File: SecurityUtility.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private static void setupTrustCerts(SslContextBuilder builder, boolean allowInsecureConnection,
        String trustCertsFilePath) throws IOException, FileNotFoundException {
    if (allowInsecureConnection) {
        builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    } else {
        if (trustCertsFilePath != null && trustCertsFilePath.length() != 0) {
            try (FileInputStream input = new FileInputStream(trustCertsFilePath)) {
                builder.trustManager(input);
            }
        } else {
            builder.trustManager((File) null);
        }
    }
}
 
Example 10
Source File: TransportSupport.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new Netty SslContext using the options specific in the given TransportOptions
 * instance.
 *
 * @param options
 *        the configured options used to create the SslContext.
 *
 * @return a new SslContext instance.
 *
 * @throws Exception if an error occurs while creating the context.
 */
public static SslContext createOpenSslContext(TransportOptions options) throws Exception {
    try {
        String contextProtocol = options.getContextProtocol();
        LOG.trace("Getting SslContext instance using protocol: {}", contextProtocol);

        KeyManagerFactory keyManagerFactory = loadKeyManagerFactory(options, SslProvider.OPENSSL);
        TrustManagerFactory trustManagerFactory = loadTrustManagerFactory(options);
        SslContextBuilder builder = SslContextBuilder.forClient().sslProvider(SslProvider.OPENSSL);

        // TODO - There is oddly no way in Netty right now to get the set of supported protocols
        //        when creating the SslContext or really even when creating the SSLEngine.  Seems
        //        like an oversight, for now we call it with TLSv1.2 so it looks like we did something.
        if (options.getContextProtocol().equals(TransportOptions.DEFAULT_CONTEXT_PROTOCOL)) {
            builder.protocols("TLSv1.2");
        } else {
            builder.protocols(options.getContextProtocol());
        }
        builder.keyManager(keyManagerFactory);
        builder.trustManager(trustManagerFactory);

        return builder.build();
    } catch (Exception e) {
        LOG.error("Failed to create SslContext: {}", e, e);
        throw e;
    }
}
 
Example 11
Source File: SignatureSourceServer.java    From compass with GNU Affero General Public License v3.0 5 votes vote down vote up
public void start() throws IOException {
  NettyServerBuilder builder =
      NettyServerBuilder.forPort(config.port)
          .addService(new SignatureSourceImpl(signatureSource));

  if (!config.plaintext) {
    if (config.certChain == null || config.certChain.isEmpty()) {
      throw new IllegalArgumentException("-certChain is required if not running in plaintext mode");
    }

    if (config.privateKey == null || config.privateKey.isEmpty()) {
      throw new IllegalArgumentException("-privateKey is required if not running in plaintext mode");
    }

    SslContextBuilder sslClientContextBuilder = SslContextBuilder.forServer(new File(config.certChain),
        new File(config.privateKey));
    if (config.trustCertCollection != null) {
      sslClientContextBuilder.trustManager(new File(config.trustCertCollection));
      sslClientContextBuilder.clientAuth(ClientAuth.REQUIRE);
    }

    builder = builder.sslContext(GrpcSslContexts.configure(sslClientContextBuilder,
        SslProvider.OPENSSL).build());
  }

  server = builder.build();
  server.start();

  log.info("Server started, listening on " + config.port);

  Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    System.err.println("*** shutting down gRPC server since JVM is shutting down");
    SignatureSourceServer.this.stop();
    System.err.println("*** server shut down");
  }));
}
 
Example 12
Source File: HelloWorldMutualTlsServiceTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void init() throws SSLException {
    SslContextBuilder builder = GrpcSslContexts.forClient();
    builder.trustManager(new File("src/main/resources/tls/ca.pem"));
    builder.keyManager(new File("src/main/resources/tls/client.pem"),
            new File("src/main/resources/tls/client.key"));
    SslContext context = builder.build();

    channel = NettyChannelBuilder.forAddress("localhost", 9000)
            .sslContext(context)
            .build();
}
 
Example 13
Source File: HelloWorldTlsServiceTest.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void init() throws SSLException {
    SslContextBuilder builder = GrpcSslContexts.forClient();
    builder.trustManager(new File("src/main/resources/tls/ca.pem"));
    SslContext context = builder.build();

    channel = NettyChannelBuilder.forAddress("localhost", 9000)
            .sslContext(context)
            .build();
}
 
Example 14
Source File: DefaultOpenDistroSecurityKeyStore.java    From deprecated-security-ssl with Apache License 2.0 5 votes vote down vote up
private SslContext buildSSLServerContext(final PrivateKey _key, final X509Certificate[] _cert,
        final X509Certificate[] _trustedCerts, final Iterable<String> ciphers, final SslProvider sslProvider,
        final ClientAuth authMode) throws SSLException {

    final SslContextBuilder _sslContextBuilder = SslContextBuilder.forServer(_key, _cert).ciphers(ciphers)
            .applicationProtocolConfig(ApplicationProtocolConfig.DISABLED)
            .clientAuth(Objects.requireNonNull(authMode)) // https://github.com/netty/netty/issues/4722
            .sessionCacheSize(0).sessionTimeout(0).sslProvider(sslProvider);

    if (_trustedCerts != null && _trustedCerts.length > 0) {
        _sslContextBuilder.trustManager(_trustedCerts);
    }

    return buildSSLContext0(_sslContextBuilder);
}
 
Example 15
Source File: TwoWaySSLOpenSSLIT.java    From qonduit with Apache License 2.0 5 votes vote down vote up
protected SSLSocketFactory getSSLSocketFactory() throws Exception {
    SslContextBuilder builder = SslContextBuilder.forClient();
    builder.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED);
    // Use server cert / key on client side.
    builder.keyManager(serverCert.key(), (String) null, serverCert.cert());
    builder.sslProvider(SslProvider.JDK);
    builder.trustManager(clientTrustStoreFile); // Trust the server cert
    SslContext ctx = builder.build();
    Assert.assertTrue(ctx.isClient());
    JdkSslContext jdk = (JdkSslContext) ctx;
    SSLContext jdkSslContext = jdk.context();
    return jdkSslContext.getSocketFactory();
}
 
Example 16
Source File: Balancer.java    From timely with Apache License 2.0 5 votes vote down vote up
protected SslContext createSSLContext(BalancerConfiguration config) throws Exception {

        ServerSsl sslCfg = config.getSecurity().getServerSsl();
        Boolean generate = sslCfg.isUseGeneratedKeypair();
        SslContextBuilder ssl;
        if (generate) {
            LOG.warn("Using generated self signed server certificate");
            Date begin = new Date();
            Date end = new Date(begin.getTime() + 86400000);
            SelfSignedCertificate ssc = new SelfSignedCertificate("localhost", begin, end);
            ssl = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey());
        } else {
            String cert = sslCfg.getCertificateFile();
            String key = sslCfg.getKeyFile();
            String keyPass = sslCfg.getKeyPassword();
            if (null == cert || null == key) {
                throw new IllegalArgumentException("Check your SSL properties, something is wrong.");
            }
            ssl = SslContextBuilder.forServer(new File(cert), new File(key), keyPass);
        }

        ssl.ciphers(sslCfg.getUseCiphers());

        // Can't set to REQUIRE because the CORS pre-flight requests will fail.
        ssl.clientAuth(ClientAuth.OPTIONAL);

        Boolean useOpenSSL = sslCfg.isUseOpenssl();
        if (useOpenSSL) {
            ssl.sslProvider(SslProvider.OPENSSL);
        } else {
            ssl.sslProvider(SslProvider.JDK);
        }
        String trustStore = sslCfg.getTrustStoreFile();
        if (null != trustStore) {
            if (!trustStore.isEmpty()) {
                ssl.trustManager(new File(trustStore));
            }
        }
        return ssl.build();
    }
 
Example 17
Source File: TwoWaySSLOpenSSLIT.java    From timely with Apache License 2.0 5 votes vote down vote up
protected SSLSocketFactory getSSLSocketFactory() throws Exception {
    SslContextBuilder builder = SslContextBuilder.forClient();
    builder.applicationProtocolConfig(ApplicationProtocolConfig.DISABLED);
    // Use server cert / key on client side.
    builder.keyManager(serverCert.key(), (String) null, serverCert.cert());
    builder.sslProvider(SslProvider.JDK);
    builder.trustManager(clientTrustStoreFile); // Trust the server cert
    SslContext ctx = builder.build();
    Assert.assertTrue(ctx.isClient());
    Assert.assertTrue(ctx instanceof JdkSslContext);
    JdkSslContext jdk = (JdkSslContext) ctx;
    SSLContext jdkSslContext = jdk.context();
    return jdkSslContext.getSocketFactory();
}
 
Example 18
Source File: TLSChannelBuilder.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public NettyChannelBuilder build(
    NettyChannelBuilder managedChannelBuilder) throws AgentPackageNotFoundException, SSLException {
    File caFile = new File(AgentPackagePath.getPath(), CA_FILE_NAME);
    if (caFile.exists() && caFile.isFile()) {
        SslContextBuilder builder = GrpcSslContexts.forClient();
        builder.trustManager(caFile);
        managedChannelBuilder = managedChannelBuilder.negotiationType(NegotiationType.TLS)
                                                     .sslContext(builder.build());
    }
    return managedChannelBuilder;
}
 
Example 19
Source File: ListenGRPC.java    From nifi with Apache License 2.0 4 votes vote down vote up
@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();
    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(SslContextFactory.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();
}
 
Example 20
Source File: TestGRPCClient.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Build a channel with the given host and port and optional ssl properties.
 *
 * @param host          the host to establish a connection with
 * @param port          the port on which to communicate with the host
 * @param sslProperties the properties by which to establish an ssl connection
 * @return a constructed channel
 */
public static ManagedChannel buildChannel(final String host, final int port, final Map<String, String> sslProperties)
        throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException, UnrecoverableKeyException {
    NettyChannelBuilder channelBuilder = NettyChannelBuilder.forAddress(host, port)
            .directExecutor()
            .compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance())
            .userAgent("testAgent");

    if (sslProperties != null) {
        SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

        if(sslProperties.get(StandardSSLContextService.KEYSTORE.getName()) != null) {
            final KeyManagerFactory keyManager = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            final KeyStore keyStore = KeyStore.getInstance(sslProperties.get(StandardSSLContextService.KEYSTORE_TYPE.getName()));
            final String keyStoreFile = sslProperties.get(StandardSSLContextService.KEYSTORE.getName());
            final String keyStorePassword = sslProperties.get(StandardSSLContextService.KEYSTORE_PASSWORD.getName());
            try (final InputStream is = new FileInputStream(keyStoreFile)) {
                keyStore.load(is, keyStorePassword.toCharArray());
            }
            keyManager.init(keyStore, keyStorePassword.toCharArray());
            sslContextBuilder = sslContextBuilder.keyManager(keyManager);
        }

        if (sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName()) != null) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            final KeyStore trustStore = KeyStore.getInstance(sslProperties.get(StandardSSLContextService.TRUSTSTORE_TYPE.getName()));
            final String trustStoreFile = sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName());
            final String trustStorePassword = sslProperties.get(StandardSSLContextService.TRUSTSTORE_PASSWORD.getName());
            try (final InputStream is = new FileInputStream(trustStoreFile)) {
                trustStore.load(is, trustStorePassword.toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder = sslContextBuilder.trustManager(trustManagerFactory);
        }

        final String clientAuth = sslProperties.get(NEED_CLIENT_AUTH);
        if (clientAuth == null) {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
        } else {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.valueOf(clientAuth));
        }
        sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder);
        channelBuilder = channelBuilder.sslContext(sslContextBuilder.build());
    } else {
        channelBuilder.usePlaintext(true);
    }
    return channelBuilder.build();
}