简体   繁体   中英

How to enable ssl in grpc with java using keystore

New to gRPC using java and I am not able to find a way how to enable ssl while using truststore and clientstore. I have been able to enable ssl by pointing to individual certificates but not using the truststore. Any leads will be really helpful.

You only need to convert the KeyStore for CA cert (truststore) to a TrustManagerFactory and the KeyStore for client cert/key (clientstore) to a KeyManagerFactory .

The former can be done with

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

and the latter can be done with

KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(clientstore, password);

Then, if you are using Netty transport, you can build the SslContext with

SslContext sslContext = GrpcSslContexts.forClient().trustManager(tmf).keyManager(kmf).build();

See its SslContextBuilder Javadoc .

Lastly, build gRPC channel with

NettyChannelBuilder.forAddress(host, port).sslContext(sslContext).build();

If you are using Okhttp transport, you need to build the SSLSocketFactory with

SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
SSLSocketFactory sslSocketFactory = context. getSocketFactory()

and build gRPC channel with

OkHttpChannelBuilder.forAddress(host, port).sslSocketFactory(sslSocketFactory).build();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM