无法连接到https(SSL)

时间:2019-05-14 10:11:35

标签: android ssl https

此代码有什么问题,我无法从WebView打开https URL。 我将证书添加到src / res / raw中,名称为“ my_ca.crt”。

错误

I/X509Util: Failed to validate the certificate chain, error: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

代码

val cf = CertificateFactory.getInstance("X.509")
        val inputS = context?.resources?.openRawResource(R.raw.my_ca)
        val caInput = BufferedInputStream(inputS)
        val ca = cf.generateCertificate(caInput)

        // Create a KeyStore containing our trusted CAs
        val keyStoreType = KeyStore.getDefaultType()
        val trustedKeyStore = KeyStore.getInstance(keyStoreType)
        trustedKeyStore.load(null, null)
        trustedKeyStore.setCertificateEntry("my_ca", ca)


        // Create a TrustManager that trusts the CAs in our KeyStore
        val tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm()
        tmf = TrustManagerFactory.getInstance(tmfAlgorithm)
        tmf?.init(trustedKeyStore)

        // Create an SSLContext that uses our TrustManager
        val sslContext = SSLContext.getInstance("TLS") //"SSL" is also not working
        sslContext.init(null, tmf?.getTrustManagers(), null);

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.socketFactory)

        web_view.loadUrl(url) 

0 个答案:

没有答案