Trust Anchor not found for Android SSL Connection

后端 未结 17 1087
囚心锁ツ
囚心锁ツ 2020-11-22 05:06

I am trying to connect to an IIS6 box running a godaddy 256bit SSL cert, and I am getting the error :

java.security.cert.CertPathValidatorException: Trust an         


        
17条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 05:14

    In Gingerbread phones, I always get this error: Trust Anchor not found for Android SSL Connection, even if I setup to rely on my certificate.

    Here is the code I use (in Scala language):

    object Security {
        private def createCtxSsl(ctx: Context) = {
            val cer = {
                val is = ctx.getAssets.open("mycertificate.crt")
                try
                    CertificateFactory.getInstance("X.509").generateCertificate(is)
                finally
                    is.close()
            }
            val key = KeyStore.getInstance(KeyStore.getDefaultType)
            key.load(null, null)
            key.setCertificateEntry("ca", cer)
    
            val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
        tmf.init(key)
    
            val c = SSLContext.getInstance("TLS")
            c.init(null, tmf.getTrustManagers, null)
            c
        }
    
        def prepare(url: HttpURLConnection)(implicit ctx: Context) {
            url match {
                case https: HttpsURLConnection ⇒
                    val cSsl = ctxSsl match {
                        case None ⇒
                            val res = createCtxSsl(ctx)
                            ctxSsl = Some(res)
                            res
                        case Some(c) ⇒ c
                    }
                    https.setSSLSocketFactory(cSsl.getSocketFactory)
                case _ ⇒
            }
        }
    
        def noSecurity(url: HttpURLConnection) {
            url match {
                case https: HttpsURLConnection ⇒
                    https.setHostnameVerifier(new HostnameVerifier {
                        override def verify(hostname: String, session: SSLSession) = true
                    })
                case _ ⇒
            }
        }
    }
    

    and here is the connection code:

    def connect(securize: HttpURLConnection ⇒ Unit) {
        val conn = url.openConnection().asInstanceOf[HttpURLConnection]
        securize(conn)
        conn.connect();
        ....
    }
    
    try {
        connect(Security.prepare)
    } catch {
        case ex: SSLHandshakeException /*if ex.getMessage != null && ex.getMessage.contains("Trust anchor for certification path not found")*/ ⇒
            connect(Security.noSecurity)
    }
    

    Basically, I setup to trust on my custom certificate. If that fails, then I disable security. This is not the best option, but the only choice I know with old and buggy phones.

    This sample code, can be easily translated into Java.

提交回复
热议问题