我在尝试将 grpc java 客户端连接到远程服务器时遇到错误。
我正在使用:
implementation 'io.grpc:grpc-okhttp:1.29.0'
所以我也假设这可能与示例中主要用于 android 相关,而我的程序是一个纯 java 应用程序,不涉及 android。
这是我的代码:
KeyStore keyStore = KeyStore.getInstance("PKCS12");
char[] password = "passwordgoeshere".toCharArray();
InputStream clientCertStream = new FileInputStream("file.p12");
InputStream caCertStream = new FileInputStream("file.pem");
keyStore.load(clientCertStream, password);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, password);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Collection<X509Certificate> certificates = (Collection<X509Certificate>) cf.generateCertificates(caCertStream);
for(X509Certificate certificate: certificates) {
keyStore.setCertificateEntry("caCert", certificate);
}
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
final SSLSocketFactory sslSocketFactory = sc.getSocketFactory();
ManagedChannelBuilder builder =
OkHttpChannelBuilder.forAddress("host", port)
.sslSocketFactory(sslSocketFactory)
.connectionSpec(ConnectionSpec.MODERN_TLS)
.hostnameVerifier((s, sslSession) -> true);
return builder.build();
这些是我的错误:
WARNING: Unable to find Conscrypt
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
io.grpc.StatusRuntimeException: UNAVAILABLE
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
最佳答案
错误消息告诉我这只是信任链验证失败的问题,即来自远程服务器的证书不受您的客户端信任。确保服务器 CA 的根证书存在于您的信任存储区 (TrustManager) 中。
关于java - 使用 okhttpchannelbuilder 相互身份验证 grpc-java tls 客户端到远程主机的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61812878/