访问IP地址时发生HttpsURLConnection,SSLPeerUnverifiedException

时间:2020-09-14 11:04:45

标签: android ssl-certificate android-security trustmanager

当HttpsURLConnection尝试使用IP地址连接到服务器时,发生以下异常:

        val is : InputStream
        var tmf: TrustManagerFactory? = null

        try {
            is = mContext.resources.assets.open("cacert.crt")
            val cf = CertificateFactory.getInstance("X.509")
            val caCert = cf.generateCertificate(`is`) as X509Certificate

            // CA certificate is used to authenticate server
            val caKs = KeyStore.getInstance(KeyStore.getDefaultType())
            caKs.load(null, null)
            caKs.setCertificateEntry("ca", caCert)
            tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
            tmf!!.init(caKs)

        } catch (e: Exception) {
            e.printStackTrace()
        }

        // POST body
        val body = mContext.getString(R.string.post_json, mOnePass)

        val url_str = "192.168.10.1/app_auth.html"

        val outputStream: OutputStream? = null
        var inputStream: InputStream? = null
        val ps: PrintStream? = null

        var connection: HttpsURLConnection? = null
        try {
            // Not used for safety
//            val hostnameVerifier = HostnameVerifier { hostname, session -> true }

            val url = URL(url_str)
            connection = url.openConnection() as HttpsURLConnection
            connection.requestMethod = "POST"
//            connection.hostnameVerifier = hostnameVerifier
            connection.connectTimeout = 30000
            connection.readTimeout = 30000
            // set trustManager from crt file
            connection.sslSocketFactory = RNSSLSocketFactory(null, tmf!!.trustManagers)

            // Header
            connection.setRequestProperty("Content-Length", body.toByteArray(charset("UTF-8")).size.toString())
            connection.setRequestProperty("Content-Type", "application/json")
            connection.setRequestProperty("app-key", mOnePass)

            connection.doOutput = true
            connection.doInput = true

            // POST
            val ops = connection.outputStream       // Exception
            val printStream = PrintStream(ops)
            printStream.print(body)
            printStream.flush()
            printStream.close()

.
.
.

错误

 javax.net.ssl.SSLPeerUnverifiedException: Hostname 192.168.10.3 not verified:
     certificate: sha1/Zh36HM6MnD49n1NVQ26ZX8BcmRA=
     DN: CN=test,OU=aa,O=bb,L=Shinjuku,ST=Tokyo,C=JP
     subjectAltNames: []

我看到一篇文章,有必要将证书的CN与IP地址进行匹配,但是要连接的服务器的IP地址可能会发生变化,并且很难将证书的CN设置为CN。

感谢您的帮助。

0 个答案:

没有答案
相关问题