keywords:android https 双向认证android GRPC https 双向认证
ManagedChannel channel = OkHttpChannelBuilder.forAddress("xxx",yyy) .overrideAuthority("zzz") .sslSocketFactory(sslFactory) .build();
1、千万不要像官网案例那样设置setPlaintext(true),这个是设置明文,我们用的是密文
2、xxx是服务器的ip,yyy是端口号,zzz是domain(这些参数服务端都会提供给你)
特别注意这个overrideAuthority一定要调用,覆盖hostname来匹配服务器的证书
3、sslSocketFactory这个方法就是设置密钥的方法。一般服务端会提供个.pem的密钥文件,放在raw中。我们把这个密钥设置到OkHttpChannelBuilder中即可以访问服务器了,关于sslSocketFactory 网上可以搜索到很多有关的内容。
cert files gen:
# Generates client.crt which is the clientCertChainFile for the client (need for mutual TLS only) openssl x509 -passin pass:1111 -req -days 365 -in client.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out client.crt echo Remove passphrase from client key: openssl rsa -passin pass:1111 -in client.key -out client.key echo Converting the private keys to X.509: # Generates client.pem which is the clientPrivateKeyFile for the Client (needed for mutual TLS only) openssl pkcs8 -topk8 -nocrypt -in client.key -out client.pem # Generates server.pem which is the privateKeyFile for the Server openssl pkcs8 -topk8 -nocrypt -in server.key -out server.pem
refs:
gRPC Android SSL/TLS Demo(Android上带有SSL/TLS加密的gRPC使用详解)
https://www.jianshu.com/p/2873a8349ca0
src demo:
https://github.com/grpc/grpc-java/blob/015b2fffa31995ff7923b4076f9324d464b7d827/android-interop-testing/app/src/main/java/io/grpc/android/integrationtest/TesterOkHttpChannelBuilder.java
grpc android mutual tls, how to send client certificate and key to server #3887
https://github.com/grpc/grpc-java/issues/3887
OkHttpChannelBuilder API Doc
https://grpc.io/grpc-java/javadoc/io/grpc/okhttp/OkHttpChannelBuilder.html#sslSocketFactory-javax.net.ssl.SSLSocketFactory-
NettyServerBuilder API Doc
https://grpc.io/grpc-java/javadoc/io/grpc/netty/NettyServerBuilder.html#sslContext-io.netty.handler.ssl.SslContext-
https://github.com/grpc/grpc-java/tree/master/examples/example-tls
Android HTTPS SSL双向验证(自签名证书) Android HTTPS SSL双向验证(CA根证书)
https://github.com/Frank-Zhu/AndroidHttpsDemo
Aandroid中https请求的单向认证和双向认证
https://blog.csdn.net/u011394071/article/details/52880062
基于Retrofit实现HTTPS思路 由于Retrofit是基于OkHttp实现的,因此想通过Retrofit实现HTTPS需要给Retrofit设置一个OkHttp代理对象用于处理HTTPS的握手过程。代理代码如下:
OkHttpClient okHttpClient = new OkHttpClient.Builder() .sslSocketFactory(SSLHelper.getSSLCertifcation(context))//为OkHttp对象设置SocketFactory用于双向认证 .hostnameVerifier(new UnSafeHostnameVerifier()) .build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://10.2.8.56:8443") .addConverterFactory(GsonConverterFactory.create())//添加 json 转换器 .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//添加 RxJava 适配器 .client(okHttpClient)//添加OkHttp代理对象 .build();
Android HTTPS 自制证书实现双向认证(OkHttp + Retrofit + Rxjava)
https://www.jianshu.com/p/64172ccfb73b
原文地址:https://www.cnblogs.com/bluestorm/p/10332265.html