如何在使用Java的情况下通过密钥库启用gRPC中的SSL。

huangapple go评论68阅读模式
英文:

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();

huangapple
  • 本文由 发表于 2020年9月22日 18:58:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/64008293.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定