我想在我的GRPC服务器上设置SSL。 为此,我需要证书链和pkcs8私钥。
我已经执行以下操作:
openssl genrsa -des3 -out ca.key 4096
openssl req -new -x509 -days 365 -key ca.key -out ca.crt
openssl genrsa -des3 -out server.key 4096
openssl req-新-key server.key -out server.csr
openssl x509 -req -days 365 -in server.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out server.crt
openssl rsa -in server.key -out server.key
openssl pkcs8 -topk8 -nocrypt-输入server.key -out pkcs8_key.pem
现在我有了我的 server.cert 和 pkcs8_key.pem 文件,我已经这样创建了服务器:
InputStream certChain = MyServer.class.getResourceAsStream("/server.crt");
InputStream privateKey = MyServer.class.getResourceAsStream("/pkcs8_key.pem");
SslContext sslContext = GrpcSslContexts.forServer(certChain, privateKey, "password").build();
Server server = NettyServerBuilder.forPort(8080)
.sslContext(sslContext)
.addService(new ChatService())
.addService(new HelloWorldService())
.useTransportSecurity(certChain, privateKey)
.build();
类路径已正确配置。
我得到的错误堆栈:
Exception in thread "main" java.lang.IllegalArgumentException: Input stream does not contain valid private key.
at io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder.keyManager(SslContextBuilder.java:296)
at io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder.forServer(SslContextBuilder.java:104)
at io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts.forServer(GrpcSslContexts.java:162)
at server.MyServer.main(MyServer.java:20)
Caused by: java.io.IOException: overrun, bytes = 2353
at javax.crypto.EncryptedPrivateKeyInfo.<init>(EncryptedPrivateKeyInfo.java:92)
at io.grpc.netty.shaded.io.netty.handler.ssl.SslContext.generateKeySpec(SslContext.java:978)
at io.grpc.netty.shaded.io.netty.handler.ssl.SslContext.getPrivateKeyFromByteBuffer(SslContext.java:1034)
at io.grpc.netty.shaded.io.netty.handler.ssl.SslContext.toPrivateKey(SslContext.java:1024)
at io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder.keyManager(SslContextBuilder.java:294)
... 3 more
答案 0 :(得分:0)
此行引起了异常:
SslContext sslContext = GrpcSslContexts
.forServer(certChain, privateKey, "password").build();
由于您的pkcs8密钥没有密码,因此您不应传递密码,而应使用两种参数的方法:
SslContext sslContext = GrpcSslContexts
.forServer(certChain, privateKey).build();
请注意,呼叫useTransportSecurity()
将覆盖对sslContext()
的呼叫,因此您不应该同时呼叫这两个呼叫。调用两者都将在当前代码中中断,因为forServer()
将消耗并关闭提供的InputStream
,因此您需要将关闭的流传递给useTransportSecurity()
。