Using gRPC with JKS
What's inside this article
⌄
- How to use gRPC with JSK
- GRPC Java keystore setup
- GRPC SSL JKS configuration
- GRPC secure connection JSK
gRPC doesn’t support JKS out of the box, but there is a workaround. Below is an example of how to use gRPC and JKS.
Server side
GrpcServer.java:
1private static final String keyStorePath = "keystore.jks";
2
3private static final String keyStorePass = "secret123";
4
5public void startServer() {
6 try {
7 ServerBuilder<?> builder = NettyServerBuilder
8 .forPort(2185)
9 .sslContext(buildGRpcSslContext())
10 .addService(service);
11 server = builder.build();
12 server.start();
13 } catch (Exception e) {
14 log.error("Can't start gRPC server", e);
15 }
16}
17
18private SslContext buildGRpcSslContext() throws Exception {
19 log.info("Building gRPC SSL context");
20 KeyStore keyStore = KeyStore.getInstance("JKS");
21 keyStore.load(new FileInputStream(keyStorePath), keyStorePass.toCharArray());
22 KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
23 keyManagerFactory.init(keyStore, keyStorePass.toCharArray());
24 return GrpcSslContexts.configure(SslContextBuilder.forServer(keyManagerFactory), SslProvider.OPENSSL).build();
25}
Client side
If you don’t need to use custom truststore, you need to do nothing. If you need to use custom truststore, use the example below:
GrpcClient.java:
1NettyChannelBuilder.forPort(2185)
2 .sslContext(GrpcSslContexts.configure(SslContextBuilder.forServer(trustManagerFactory)).build())
3 .build();
You can use trustManagerFactory object creation example from the server side code, just use TrustManagerFactory instead of KeyManagerFactory.