Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/206.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
未找到Android SSL连接的信任锚点_Android_Ssl_Ssl Certificate - Fatal编程技术网

未找到Android SSL连接的信任锚点

未找到Android SSL连接的信任锚点,android,ssl,ssl-certificate,Android,Ssl,Ssl Certificate,我正在尝试连接到运行godaddy 256bit SSL证书的IIS6盒,但收到错误: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found. 我一直在试图确定是什么原因造成的,但现在还没有定论 以下是我的联系方式: httpsurl连接接头; conn=(HttpsURLConnection)(新URL(mURL)).openConnection(); 连接设置

我正在尝试连接到运行godaddy 256bit SSL证书的IIS6盒,但收到错误:

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
我一直在试图确定是什么原因造成的,但现在还没有定论

以下是我的联系方式:

httpsurl连接接头;
conn=(HttpsURLConnection)(新URL(mURL)).openConnection();
连接设置连接超时(20000);
conn.setDoInput(真);
连接设置输出(真);
连接();
字符串tempString=toString(conn.getInputStream());

@Chrispix的解决方案很危险<强>信任所有证书允许任何人做中间人攻击!只需将任何证书发送到客户端,它就会接受它

将您的证书添加到自定义信任管理器,如本文所述:


尽管与自定义证书建立安全连接要复杂得多,但它将为您提供所需的SSL加密安全性,而不会有中间人攻击的危险。p> 与公认的答案相反,您不需要自定义信任管理器,您需要修复服务器配置

我在使用错误安装的dynadot/alphassl证书连接到Apache服务器时遇到了相同的问题。我正在使用HttpsUrlConnection(Java/Android)进行连接,这是-

javax.net.ssl.SSLHandshakeException: 
  java.security.cert.CertPathValidatorException: 
    Trust anchor for certification path not found.
实际问题是服务器配置错误-使用或类似的方法进行测试,它甚至会告诉您解决方案:

“该证书未由受信任的机构签名(检查Mozilla的根存储)。如果您是从受信任的机构购买该证书,您可能只需要安装一个或多个中间证书。。请与您的证书提供商联系,以获得为您的服务器平台执行此操作的帮助。”

您还可以使用openssl检查证书:

openssl s_客户端-调试-连接www.thedomaintocheck.com:443

您可能会看到:

验证返回代码:21(无法验证第一个证书)

在输出的前面:

depth=0 OU = Domain Control Validated, CN = www.thedomaintocheck.com
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 OU = Domain Control Validated, CN = www.thedomaintocheck.com
verify error:num=27:certificate not trusted
verify return:1
depth=0 OU = Domain Control Validated, CN = www.thedomaintocheck.com
verify error:num=21:unable to verify the first certificate`
证书链将仅包含1个元素(您的证书):

。。。但应将链中的签名机构引用回Android信任的机构(Verisign、GlobalSign等):

配置服务器的说明(和中间证书)通常由颁发证书的机构提供,例如:


安装证书颁发者提供的中间证书后,我现在使用HttpsUrlConnection连接时没有错误。

我收到的错误消息与此类似,但原因是自签名证书已过期。 当尝试使用openssl客户端时,它给出了我在检查firefox中的证书对话框时忽略的原因


因此,一般来说,如果密钥库中有证书且证书“有效”,则会出现此错误。

在姜饼手机中,我总是会遇到此错误:
未找到Android SSL连接的信任锚点
,即使我设置为依赖我的证书

以下是我使用的代码(Scala语言):

这是连接代码:

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)
}
基本上,我设置为信任我的自定义证书。如果失败,那么我将禁用安全性。这不是最好的选择,但我所知道的唯一的选择是老式和有问题的手机


这个示例代码可以很容易地翻译成Java。

我发现同样的问题是,我提供的certificate.crt文件缺少一个中间证书。所以我向我的服务器管理员询问了所有的.crt文件,然后按相反的顺序将它们关联起来

前。 1.Root.crt 2.Inter.crt 3.myCrt.crt

在windows中,我执行 复制Inter.crt+Root.crt newCertificate.crt

(这里我忽略了myCrt.crt)

然后,我通过inputstream将newCertificate.crt文件提供到代码中。
工作完成。

您可以在运行时信任特定的证书。
**Set proper alias name**
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509","BC");
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
            String alias = cert.getSubjectX500Principal().getName();
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);
只需从服务器下载,放入资产并使用以下方式加载:

在上面的示例中,我使用了
OkHttpClient
,但是
SSLContext
可以用于Java中的任何客户端


如果您有任何问题,请随时提问。我是这个小图书馆的作者。

基于最新Android文档的更新(2017年3月):

   public  okhttp3.OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate 
   certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] {
                new X509TrustManager() {
                    @Override
                    public void 
   checkClientTrusted(java.security.cert.X509Certificate[] chain, 
   String authType) throws CertificateException {
                    }

                    @Override
                    public void 
  checkServerTrusted(java.security.cert.X509Certificate[] chain, 
  String authType) throws CertificateException {
                    }

                    @Override
                    public java.security.cert.X509Certificate[] 
   getAcceptedIssuers() {
                        return new 
  java.security.cert.X509Certificate[]{};
                    }
                }
        };

        // Install the all-trusting trust manager
        final SSLContext sslContext = 
  SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new 
  java.security.SecureRandom());

        // Create an ssl socket factory with our all-trusting 
       manager
        final SSLSocketFactory sslSocketFactory = 
       sslContext.getSocketFactory();

        okhttp3.OkHttpClient.Builder builder = new 
      okhttp3.OkHttpClient.Builder();
        builder.sslSocketFactory(sslSocketFactory, 
      (X509TrustManager)trustAllCerts[0]);
        builder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession 
       session) {
                return true;
            }
        });

        okhttp3.OkHttpClient okHttpClient = builder.build();
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
    @SuppressLint("TrulyRandom")
    public static void handleSSLHandshake() {
    try {
        TrustManager[] trustAllCerts = new TrustManager[]{new 
       X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }

            @Override
            public void checkClientTrusted(X509Certificate[] 
        certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] 
       certs, String authType) {
            }
        }};

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        



  HttpsURLConnection
 .setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new 
    HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
    } catch (Exception ignored) {
    }
}
当您遇到此类错误时:

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
        at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:374)
        at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:209)
        at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
        at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
        at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
        at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
        at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
        at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
        at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
问题可能是以下之一:

  • 颁发服务器证书的CA未知
  • 服务器证书不是由CA签名的,而是自签名的
  • 服务器配置缺少中间CA
  • 解决方案是教
    HttpsURLConnection
    信任一组特定的CA。怎么用?请查收


    其他正在使用
    com.loopj.android:android async http
    库中的
    AsyncHTTPClient
    的用户,请检查

    从Android客户端连接到Kurento服务器时,我遇到了同样的问题。 Kurento服务器使用jks证书,所以我必须将pem转换为它。 作为转换的输入,我使用了cert.pem文件,它导致了这样的错误。
    但是如果使用fullchain.pem而不是cert.pem,一切都可以。

    回复非常老的帖子。但如果以上这些都不起作用的话,也许这会对一些新手有所帮助

    解释:我知道没有人想要解释的废话;而是解决办法。但在一种情况下,您试图从本地机器访问服务,而远程机器不信任您的机器。您的请求需要从远程服务器获得信任

    解决方案:以下解决方案假设您满足以下条件

  • 正在尝试从本地计算机访问远程api
  • 您正在构建Android应用程序
  • 您的远程服务器正在进行代理筛选(您在浏览器设置中使用代理来访问远程api服务,通常是stagin
    OkHttpClient client = new OkHttpClient();
    SSLContext sslContext = SslUtils.getSslContextForCertificateFile(context, "BPClass2RootCA-sha2.cer");
    client.setSslSocketFactory(sslContext.getSocketFactory());
    
    javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
            at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:374)
            at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:209)
            at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:478)
            at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433)
            at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
            at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
            at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
            at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
            at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271)
    
    productFlavors {
        staging {
            applicationId "com.yourapplication.package"
            manifestPlaceholders = [icon: "@drawable/ic_launcher"]
            buildConfigField "boolean", "CATALYST_DEBUG", "true"
            buildConfigField "boolean", "ALLOW_INVALID_CERTIFICATE", "true"
        }
        production {
            buildConfigField "boolean", "CATALYST_DEBUG", "false"
            buildConfigField "boolean", "ALLOW_INVALID_CERTIFICATE", "false"
        }
    }
    
    mySSLContext.init(null, trustAllCerts, null); 
    
    private final TrustManager[] trustAllCerts= new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[]{};
        }
    
        public void checkClientTrusted(X509Certificate[] chain,
                                       String authType) throws CertificateException {
        }
    
        public void checkServerTrusted(X509Certificate[] chain,
                                       String authType) throws CertificateException {
        }
    } };
    
    retrofit = new Retrofit.Builder()
        .baseUrl(ApplicationData.FINAL_URL)
        .client(getUnsafeOkHttpClient().build())
        .addConverterFactory(GsonConverterFactory.create())
        .build();
    
    override fun onBuildHttpClient(httpClientBuild: OkHttpClient.Builder) {
    
            val trustManagerWrapper = createX509TrustManagerWrapper(
                arrayOf(
                    getCustomX509TrustManager(),
                    getDefaultX509TrustManager()
                )
            )
    
            printX509TrustManagerAcceptedIssuers(trustManagerWrapper)
    
            val sslSocketFactory = createSocketFactory(trustManagerWrapper)
            httpClientBuild.sslSocketFactory(sslSocketFactory, trustManagerWrapper)
    
        }
    
    import java.security.SecureRandom
    import java.security.cert.X509Certificate
    import javax.net.ssl.*
    import javax.security.cert.CertificateException
    
    object {
    
        val okHttpClient: OkHttpClient
        val gson: Gson
        val retrofit: Retrofit
    
        init {
    
            okHttpClient = getOkHttpBuilder()
                // Other parameters like connectTimeout(15, TimeUnit.SECONDS)
                .build()
    
            gson = GsonBuilder().setLenient().create()
    
            retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build()
        }
    
        fun getOkHttpBuilder(): OkHttpClient.Builder =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                OkHttpClient().newBuilder()
            } else {
                // Workaround for the error "Caused by: com.android.org.bouncycastle.jce.exception.ExtCertPathValidatorException: Could not validate certificate: Certificate expired at".
                getUnsafeOkHttpClient()
            }
    
        private fun getUnsafeOkHttpClient(): OkHttpClient.Builder =
            try {
                // Create a trust manager that does not validate certificate chains
                val trustAllCerts: Array<TrustManager> = arrayOf(
                    object : X509TrustManager {
                        @Throws(CertificateException::class)
                        override fun checkClientTrusted(chain: Array<X509Certificate?>?,
                                                        authType: String?) = Unit
    
                        @Throws(CertificateException::class)
                        override fun checkServerTrusted(chain: Array<X509Certificate?>?,
                                                        authType: String?) = Unit
    
                        override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
                    }
                )
                // Install the all-trusting trust manager
                val sslContext: SSLContext = SSLContext.getInstance("SSL")
                sslContext.init(null, trustAllCerts, SecureRandom())
                // Create an ssl socket factory with our all-trusting manager
                val sslSocketFactory: SSLSocketFactory = sslContext.socketFactory
                val builder = OkHttpClient.Builder()
                builder.sslSocketFactory(sslSocketFactory,
                    trustAllCerts[0] as X509TrustManager)
                builder.hostnameVerifier { _, _ -> true }
                builder
            } catch (e: Exception) {
                throw RuntimeException(e)
            }
    }
    
    @GlideModule
    class MyAppGlideModule : AppGlideModule() {
    
        val okHttpClient = Api.getOkHttpBuilder().build() // Api is the class written above.
        // It is better to create okHttpClient here and not use Api.okHttpClient,
        // because their settings may differ. For instance, it can use its own
        // `addInterceptor` and `addNetworkInterceptor` that can affect on a read JSON.
    
    
        override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
            registry.replace(GlideUrl::class.java, InputStream::class.java,
                OkHttpUrlLoader.Factory(okHttpClient))
        }
    }
    
    // Glide.
    implementation 'com.github.bumptech.glide:glide:4.11.0'
    implementation 'com.github.bumptech.glide:okhttp3-integration:4.11.0'
    kapt 'com.github.bumptech.glide:compiler:4.11.0'
    
    okHttpClient = getOkHttpBuilder().build()
    
    private fun getOkHttpBuilder(): OkHttpClient.Builder {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            Security.insertProviderAt(Conscrypt.newProvider(), 1)
        }
        return OkHttpClient().newBuilder()
    }
    
    // build.gradle:
    implementation 'org.conscrypt:conscrypt-android:2.5.1'
    
    try {
        ProviderInstaller.installIfNeeded(applicationContext)
        val sslContext = SSLContext.getInstance("TLSv1.2")
        sslContext.init(null, null, null)
        sslContext.createSSLEngine()
    } catch (e: GooglePlayServicesRepairableException) {
        Timber.e(e.stackTraceToString())
        // Prompt the user to install/update/enable Google Play services.
        GoogleApiAvailability.getInstance().showErrorNotification(this, e.connectionStatusCode)
    } catch (e: GooglePlayServicesNotAvailableException) {
        Timber.e(e.stackTraceToString())
        // Prompt the user to install/update/enable Google Play services.
        // GoogleApiAvailability.getInstance().showErrorNotification(this, e.errorCode)
    } catch (e: NoSuchAlgorithmException) {
        Timber.e(e.stackTraceToString())
    } catch (e: KeyManagementException) {
        Timber.e(e.stackTraceToString())
    }
    
    https://example.com/
    
    http://example.com/
    
    <domain-config>
            <domain includeSubdomains="true">PUT_YOUR_SERVER_ADDERESS</domain>
            <trust-anchors>
                <certificates src="user" />
            </trust-anchors>
    </domain-config>
    
       public  okhttp3.OkHttpClient getUnsafeOkHttpClient() {
        try {
            // Create a trust manager that does not validate 
       certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[] {
                    new X509TrustManager() {
                        @Override
                        public void 
       checkClientTrusted(java.security.cert.X509Certificate[] chain, 
       String authType) throws CertificateException {
                        }
    
                        @Override
                        public void 
      checkServerTrusted(java.security.cert.X509Certificate[] chain, 
      String authType) throws CertificateException {
                        }
    
                        @Override
                        public java.security.cert.X509Certificate[] 
       getAcceptedIssuers() {
                            return new 
      java.security.cert.X509Certificate[]{};
                        }
                    }
            };
    
            // Install the all-trusting trust manager
            final SSLContext sslContext = 
      SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new 
      java.security.SecureRandom());
    
            // Create an ssl socket factory with our all-trusting 
           manager
            final SSLSocketFactory sslSocketFactory = 
           sslContext.getSocketFactory();
    
            okhttp3.OkHttpClient.Builder builder = new 
          okhttp3.OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, 
          (X509TrustManager)trustAllCerts[0]);
            builder.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession 
           session) {
                    return true;
                }
            });
    
            okhttp3.OkHttpClient okHttpClient = builder.build();
            return okHttpClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
        @SuppressLint("TrulyRandom")
        public static void handleSSLHandshake() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{new 
           X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
    
                @Override
                public void checkClientTrusted(X509Certificate[] 
            certs, String authType) {
                }
    
                @Override
                public void checkServerTrusted(X509Certificate[] 
           certs, String authType) {
                }
            }};
    
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            
    
    
    
      HttpsURLConnection
     .setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new 
        HostnameVerifier() {
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });
        } catch (Exception ignored) {
        }
    }
    
     implementation 'com.squareup.okhttp:okhttp:2.3.0'
    implementation 'com.squareup.okhttp:okhttp-urlconnection:2.3.0'
        androidTestImplementation 'androidx.test.espresso:espresso- 
        core:3.3.0'