1.pfx转cer
openssl pkcs12 -nodes -nokeys -in xxx.pfx -passin pass:证书密码 -out xxx.cer
2.下载bouncycastle的jar包
wget http://repo2.maven.org/maven2/org/bouncycastle/bcprov-jdk16/1.46/bcprov-jdk16-1.46.jar
3.cer转bks
keytool -importcert -v -trustcacerts -file xxx.cer -alias xxx -keystore xxx.bks -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath bcprov-jdk16-1.46.jar -storetype BKS -storepass xxx
4.拷贝bks文件到res/raw文件夹下
5.生成SSLSocketFactory和X509TrustManager
fun build(context: Context): ETCASSL? {
var socketFactory: SSLSocketFactory? = null
var x509TrustManager: X509TrustManager? = null
try {
//取得SSL的SSLContext实例
val sslContext = SSLContext.getInstance("TLSv1", "AndroidOpenSSL")
//取得TrustManagerFactory的X509密钥管理器实例
val trustManager = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
//取得BKS密库实例
val keyStore = KeyStore.getInstance("BKS")
val inputStream = context.resources.openRawResource(R.raw.etca_doshare_test)
inputStream.use { keyStore.load(it, "eetrust123".toCharArray()) }
//初始化密钥管理器
trustManager.init(keyStore)
//初始化SSLContext
val trustManagers = trustManager.trustManagers
sslContext.init(null, trustManagers, null)
socketFactory = sslContext.socketFactory
x509TrustManager = trustManagers[0] as X509TrustManager
} catch (e: Exception) {
e.printStackTrace()
}
return ETCASSL(socketFactory ?: return null, x509TrustManager ?: return null, HostnameVerifier { _, _ -> true})
}
6.OkHttp配置
OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)//连接超时设置
.writeTimeout(30, TimeUnit.SECONDS)//写入超时设置
.readTimeout(30, TimeUnit.SECONDS)//读取超时设置
.sslSocketFactory(etcassl.sslSocketFactory, etcassl.trustManager)//配置SSL证书
.hostnameVerifier(etcassl.hostnameVerifier)
.addInterceptor(SignInterceptor())
.addInterceptor(TokenInterceptor())
.addInterceptor(LogInterceptor())
.build()
7.Netty配置
bootstrap?.handler(object : ChannelInitializer() {
override fun initChannel(socketChannel: SocketChannel) {
val pipeline = socketChannel.pipeline()
//配置SSL证书
ETCASSL.buildSslContext(BaseApplication.getApplicationContext())?.createSSLEngine()?.let {sslEngine->
sslEngine.useClientMode = true
sslEngine.needClientAuth = true
pipeline.addLast(SslHandler(sslEngine))
}
//心跳包
pipeline.addLast("idleStateHandler", IdleStateHandler(0, 4, 0, TimeUnit.MINUTES))
pipeline.addLast("http-codec", HttpClientCodec())
pipeline.addLast("aggregator", HttpObjectAggregator(1048576))
val handShaker = WebSocketClientHandshakerFactory.newHandshaker(
uri, WebSocketVersion.V13, null, true, DefaultHttpHeaders())
pipeline.addLast("ws-ClientProtocolHandler", WebSocketClientProtocolHandler(handShaker, false))
pipeline.addLast(LoggingHandler(LogLevel.INFO))
pipeline.addLast("clientHandler", ImsClientHandler())
}
})