英文:
How to enable ssl in grpc with java using keystore
问题
刚开始使用 Java 进行 gRPC,但我无法找到在使用信任存储和客户端存储时如何启用 SSL 的方法。我已经成功通过指向单个证书来启用 SSL,但没有使用信任存储的方法。任何线索将非常有帮助。
英文:
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.
答案1
得分: 2
你只需要将 CA 证书的 KeyStore
(信任库)转换为 TrustManagerFactory
,并将客户端证书/密钥的 KeyStore
(客户端库)转换为 KeyManagerFactory
。
前者可以通过以下方式完成:
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(truststore);
后者可以通过以下方式完成:
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(clientstore, password);
然后,如果您正在使用 Netty 传输,可以使用以下方式构建 SslContext
:
SslContext sslContext = GrpcSslContexts.forClient().trustManager(tmf).keyManager(kmf).build();
请参阅其 SslContextBuilder
Javadoc。
最后,使用以下方式构建 gRPC 通道:
NettyChannelBuilder.forAddress(host, port).sslContext(sslContext).build();
如果您正在使用 Okhttp 传输,您需要使用以下方式构建 SSLSocketFactory
:
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
SSLSocketFactory sslSocketFactory = context.getSocketFactory();
然后使用以下方式构建 gRPC 通道:
OkHttpChannelBuilder.forAddress(host, port).sslSocketFactory(sslSocketFactory).build();
英文:
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();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论