使用服务器和客户端证书以及私钥创建SSLContext

时间:2018-09-03 17:52:22

标签: android rsa keystore java-security sslcontext

我正在编写Android应用程序。它通过TLS连接到服务器。我从服务器作者那里收到了3个文件供使用(以检查通信,以后将生成密钥): -服务器证书(cacrt.crt) -客户端证书(clientcrt.crt) -客户端私钥(clientkey.key)

我正在尝试使用这些键创建SSLContext,但遇到一些问题。我无法以.crt和.key文件的格式加载它们,因此我将它们转换为BKS格式(client.bks用于客户端,server.bks用于服务器密钥)。但是在创建KeyStore KeyStoreException: KeyStore was not initialized时出现异常。

这是我的代码:

val clientCrt = CertificateFactory.getInstance("X.509").generateCertificate(resources.openRawResource(R.raw.clientcrt))
val keyManagerFactory = KeyManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
val keyStore = KeyStore.getInstance("BKS")
val keyInputClient = resources.openRawResource(R.raw.client)
keyStore.load(keyInputClient, "123456".toCharArray())
keyStore.setCertificateEntry("ca", clientCrt)
keyInputClient.close()
keyManagerFactory.init(keyStore, "123456".toCharArray())

val inputStream2 = 
val serverCrt = CertificateFactory.getInstance("X.509").generateCertificate(resources.openRawResource(R.raw.cacrt))
val keyStore2 = KeyStore.getInstance("BKS")
val keyInputServer = resources.openRawResource(R.raw.server)
keyStore.load(keyInputServer, "123456".toCharArray())
keyStore2.setCertificateEntry("ca", serverCrt)     // <--- KeyStoreException: KeyStore was not initialized
keyInputServer.close()

val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(keyStore2);

val sslContext = SSLContext.getInstance("TLS")
sslContext.init(keyManagerFactory.keyManagers, trustManagerFactory.trustManagers, SecureRandom())

您能帮我解决吗?我不知道我在做什么错。

0 个答案:

没有答案