Ошибка java security cert certpathvalidatorexception trust

Contrary to the accepted answer you do not need a custom trust manager, you need to fix your server configuration!

I hit the same problem while connecting to an Apache server with an incorrectly installed dynadot/alphassl certificate. I’m connecting using HttpsUrlConnection (Java/Android), which was throwing —

javax.net.ssl.SSLHandshakeException: 
  java.security.cert.CertPathValidatorException: 
    Trust anchor for certification path not found.

The actual problem is a server misconfiguration — test it with http://www.digicert.com/help/ or similar, and it will even tell you the solution:

«The certificate is not signed by a trusted authority (checking against Mozilla’s root store). If you bought the certificate from a trusted authority, you probably just need to install one or more Intermediate certificates. Contact your certificate provider for assistance doing this for your server platform.»

You can also check the certificate with openssl:

openssl s_client -debug -connect www.thedomaintocheck.com:443

You’ll probably see:

Verify return code: 21 (unable to verify the first certificate)

and, earlier in the output:

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`

The certificate chain will only contain 1 element (your certificate):

Certificate chain
 0 s:/OU=Domain Control Validated/CN=www.thedomaintocheck.com
  i:/O=AlphaSSL/CN=AlphaSSL CA - G2

… but should reference the signing authorities in a chain back to one which is trusted by Android (Verisign, GlobalSign, etc):

Certificate chain
 0 s:/OU=Domain Control Validated/CN=www.thedomaintocheck.com
   i:/O=AlphaSSL/CN=AlphaSSL CA - G2
 1 s:/O=AlphaSSL/CN=AlphaSSL CA - G2
   i:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA
 2 s:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA
   i:/C=BE/O=GlobalSign nv-sa/OU=Root CA/CN=GlobalSign Root CA

Instructions (and the intermediate certificates) for configuring your server are usually provided by the authority that issued your certificate, for example: http://www.alphassl.com/support/install-root-certificate.html

After installing the intermediate certificates provided by my certificate issuer I now have no errors when connecting using HttpsUrlConnection.

Comments

@valery-lavrik

@valery-lavrik
valery-lavrik

changed the title
java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

react-native: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

Nov 15, 2022

@valery-lavrik
valery-lavrik

changed the title
react-native: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

java.security.cert.CertPathValidatorException: Trust anchor for certification path not found (app in react-native)

Nov 15, 2022

Recently I was working on a chat application for the android platform, everything regarding the remote/networking implementation worked flawlessly. I used the Retrofit networking library and socket.io. At the time, the base url was without SSL (that is the HTTP scheme — http://api.example.com)

Just before we rolled out the MVP for beta testing, we acquired a domain name and enabled SSL on the server. This meant the base URL scheme became HTTPS (e.g https://api.example.com).

The change on the app to use a secured URL broke the entire app. All the endpoints were not connecting to the server successfully. Basically the network handshake process between the client and server wasn’t successful. Below is what the the error on the log was like

<-- HTTP FAILED: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

Enter fullscreen mode

Exit fullscreen mode

After doing a little research I discovered it was an issue with the server certificate not being trusted by the android system. This could be because of any of the reasons below:

  1. The Certificate Authority (CA) that issued the server certificate was unknown.

  2. The server certificate wasn’t signed by a CA, but was self signed.

  3. The server configuration is missing an intermediate CA.

In my case, this issue existed because the server certificate was self signed.

From android documentation there is a clean way to configure the app to trust your own self-signed certificates, which I will outline in 3 steps.

Step 1

Add the crt file to the raw folder.

This file will be retrieved from the server. You can request for the digital certificate from the backend engineer. It should come in a .crt extension.

crt file

Step 2

Create an XML network security config file (network_security_config.xml) like below:

XML network security config file

network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config>
        <domain includeSubdomains="true">api.example.com</domain>
        <trust-anchors>
            <certificates src="@raw/certificate" />
        </trust-anchors>
    </domain-config>
</network-security-config>

Enter fullscreen mode

Exit fullscreen mode

Step 3

Specify the network configuration settings in the Manifest.xml file of your application.

android manifest file

With these 3 steps done, you should connect seamlessly with the backend without any further issues.

Падает java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
При этом запрашиваемый домен домен имеет верифицированный сертификат.
Если бы речь шла о self-signed сертификате, то причина была бы ясна.
Объясните, что нужно делать чтобы можно было послать запрос на «нормальный» (верифицированный) домен?

UPDATE:

Так создается инстанс ретрофита:

init {
    App.getComponent().inject(this)
    val builder = OkHttpClient().newBuilder().socketFactory(getSSLConfig(App.getContext()).socketFactory)
    builder.addInterceptor(httpInterceptor)
    val client = builder.build()
    retrofit = Retrofit.Builder()
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(Net.BASE_URL.value)
            .client(client)
            .build()
}

@Throws(CertificateException::class, IOException::class, KeyStoreException::class, NoSuchAlgorithmException::class, KeyManagementException::class)
private fun getSSLConfig(context: Context): SSLContext {

    // Loading CAs from an InputStream
    var cf: CertificateFactory? = null
    cf = CertificateFactory.getInstance("X.509")

    var ca: Certificate? = null
    // I'm using Java7. If you used Java6 close it manually with finally.
    context.resources.openRawResource(R.raw.certificate_ca).use({ cert -> ca = cf.generateCertificate(cert) })

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

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

    // Creating an SSLSocketFactory that uses our TrustManager
    val sslContext = SSLContext.getInstance("TLS")
    sslContext.init(null, tmf.trustManagers, null)

    return sslContext
}

При обращении к серверу получаю Handshake failed. Что я делаю не верно?

Stacktrace:

01-19 12:50:46.578 7161-7161/ru.rst.console W/System.err: javax.net.ssl.SSLHandshakeException: Handshake failed
01-19 12:50:46.579 7161-7161/ru.rst.console W/System.err:     at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:423)
                                                              at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:281)
                                                              at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:251)
                                                              at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:151)
                                                              at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:195)
                                                              at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:121)
                                                              at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:100)
                                                              at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
                                                              at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                              at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
                                                              at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
                                                              at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                              at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
01-19 12:50:46.580 7161-7161/ru.rst.console W/System.err:     at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
                                                              at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                              at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:120)
                                                              at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                              at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
                                                              at ru.rst.console.base.http.HttpInterceptor.handleResponse(HttpInterceptor.kt:29)
                                                              at ru.rst.console.base.http.HttpInterceptor.intercept(HttpInterceptor.kt:25)
                                                              at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                              at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
                                                              at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:185)
                                                              at okhttp3.RealCall$AsyncCall.execute(RealCall.java:135)
                                                              at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
                                                              at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
                                                              at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
01-19 12:50:46.582 7161-7161/ru.rst.console W/System.err:     at java.lang.Thread.run(Thread.java:764)
                                                          Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xa5522bc0: Failure in SSL library, usually a protocol error
                                                          error:10000066:SSL routines:OPENSSL_internal:BAD_ALERT (external/boringssl/src/ssl/tls_record.c:465 0xa3078e9f:0x00000000)
                                                              at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
01-19 12:50:46.583 7161-7161/ru.rst.console W/System.err:     at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:351)
                                                            ... 27 more

The trust anchor for certification path not found Android emulator error appears due to invalid or broken user certificates in the server configuration. As a result, you cannot access the trust anchor via the certification path because your program does not recognize the location or certificates that grant permission.Trust Anchor for Certification Path Not Found

Fortunately, we found several debugging methods that remove the trust anchor for certification path not found Charles exception without causing further complications or inconveniences. In addition, we will help you recreate the trust anchor for certification path not found localhost bug using typical elements, which will help you troubleshoot the script.

Contents

  • What Causes the Trust Anchor for Certification Path Not Found Error?
    • – Broken Local Hosts on Android Applications
  • Fix the Trust Anchor for Certification Path Not Found Broken Script
    • – Checking the Certificate With Open SSL
    • – Testing the Domain on Kotlin
  • Conclusion

What Causes the Trust Anchor for Certification Path Not Found Error?

Incorrect or broken user certificates in the configuration usually cause the trust anchor for certification path not found Kotlin bug. An identical code exception also pops up on your screen due to a misconfiguration with the web server configuration files because they are related to adequate certificates.

As you can tell, the trust anchor for certification path not found Android self-signed mistake can obliterate your programming experience when working with complex files. Therefore, avoiding the error is only possible with adequate user certificates in the server configurations.

Unfortunately, the trust anchor for certification path not found. Android 7 exception launches many indicators where the project fails and which routes are distorted. Luckily, we will use the incorrect messages to troubleshoot the program, pinpoint the forgotten certification paths, and apply the debugging principles.

For instance, we confirmed the trust anchor for certification path not found. Android 6 error when connecting to an Apache server with invalid certificates. Although this process is usually full-proof and does not yield mistakes, it can affect your certificates and force the system to fail due to specific server misconfigurations.

Unfortunately, you can experience the trust anchor for certification path not found. Android 11 exception, confirming it affects many Android versions. So, let us recreate the code exception before teaching the most sophisticated debugging methods.

– Broken Local Hosts on Android Applications

You can quickly recreate the invalid exception using broken local hosts on Android applications, which confuses the paths. So, the process consists of a few steps that lead to the mistake. First, you must create a new application and try to complete a request to the API on a local host. Then, you must use the specific code that launches the certification path where the error appears.Broken Local Hosts on Android Applications

The following example provides the required script:

var httpHandler = new HttpClientHandler

{

ServerCertificateCustomValidationCallback = (o, cert, chain, errors) => true

};

//or

httpHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>

{

if (cert.Issuer.Equals(“CN=localhost”))

return true;

return errors == System.Net.Security.SslPolicyErrors.None;

};

//or

ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) =>

{

return true;

};

#else

var httpHandler = new HttpClientHandler();

#endif

Unfortunately, this input produces a log output that specifies the mistake and confirms the broken instances. You can learn more about this exception in the following syntax:56-*

System.WebException: java.security.CertPathValidatorException: Trust anchor for certification location not found.

—> Javax.Net.SSLHandshakeException: java.security.CertPathValidatorException: Trust anchor for certification location not found.

—> Java.Security.CertificateException: java.security.CertPathValidatorException: Trust anchor for certification location not found.

—> Java.Security.CertPathValidatorException: Trust anchor for certification location not found.

— End of managed Java.Security.Cert.CertPathValidatorException stack trace —

java.security.CertPathValidatorException: Trust anchor for certification location not found.

at com.org.conscrypt.TrustManagerImpl.verifyChain (TrustManager.java:661)

at com.org.conscrypt.TrustManager.checkTrustedRecursive (TrustManagerImpl.java:539)

at com.org.conscrypt.TrustManager.checkTrusted (TrustManagerImpl.java:495)

at com.org.conscrypt.TrustManager.checkTrusted (TrustManagerImpl.java:418)

at com.org.conscrypt.TrustManage.getTrustedChainForServer (TrustManagerImpl.java:339)

at android.net.config.NetworkSecurityTrustManager.checkServer (NetworkSecurityTrustManager.java:85)

at android.net.config.RootTrustManager.checkServer (RootTrustManager.java:88)

at com.org.conscrypt.Platform.checkServer (Platform.java:208)

Although we can provide the other outputs, this example is sufficient to comprehend the failed properties.

Fix the Trust Anchor for Certification Path Not Found Broken Script

You must add the certificates to a trust manager to fix this annoying exception and allow other processes. In addition, you can check the certificate path on the web page to check for issues and inconsistencies. Still, both approaches require changing the ways, which is critical when debugging the code.

Furthermore, customizing the HTTP client and using the retrofit property can achieve excellent results. Luckily, this method only requires a few changes, as shown below:

retrofit = new Retrofit.Builder()

.baseUrl(ApplicationData.FINAL_URL)

.client(getUnsafeOkHttpClient().build())

.addConverterFactory(GsonConverterFactory.create())

.build();

This is everything your script needs to clear the inconsistencies and allow all processes. Therefore, read the following example to learn about the full syntax:

public class RestAdapter {

private static Retrofit retrofit = null;

private static ApiInterface apiInterface;

public static OkHttpClient.Builder getUnsafeOkHttpClient() {

try {

final TrustManager[] trustCerts = new TrustManager[]{

new X777 TrustManager() {

@Override

public void checkClient(java.security.cert.X777 Certificate[] chain, String authType) throws CertificateException {

}

}

};

final SSLContext Context = SSLContext.getInstance(“SSL”);

Context.init (null, trustAllCerts, new java.security.SecureRandom());

final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

OkHttpClient.Builder builder = new OkHttpClient.Builder();

builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);

builder.hostnameVerifier(new HostnameVerifier() {

@Override

public boolean verify(String hostname, SSLSession session) {

return true;

}

});

return builder;

} catch (Exception e) {

throw new RuntimeException(e);

}

}

public static ApiInterface getApiClient() {

if (apiInterface == null) {

try {

retrofit = new Retrofit.Builder()

.baseUrl(ApplicationData.FINAL_URL)

.client(getUnsafeOkHttpClient().build())

.addConverterFactory(GsonConverterFactory.create())

.build();

} catch (Exception e) {

e.printStackTrace();

}

apiInterface = retrofit.create(ApiInterface.class);

}

return apiInterface;

}

}

As you can tell, this introductory solution enables all processes and repairs the certification paths. Luckily, this is one of the many debugging approaches and methods.

– Checking the Certificate With Open SSL

Another excellent debugging approach teaches you how to check the certificate with the open SSL property. This method ensures all paths are functional and the credentials are correct.Broken Local Hosts on Android Applications Fixes

You can use the following command to check the certificate:

openssl s_client -debug -connect www.WebSite.com:443

You will likely see the following output that confirms the primary certificate:

Verify return code: 34 (unable to verify the first certificate)

Depth = 1 OU = Domain Control Validated, CN = www.WebSite.com

verify error:num = 19: cannot get local issuer certificate

verify return:1

depth = 1 OU = Domain Control Validated, CN = www.WebSite.com

verify error:num = 31:certificate not trusted

verify return:1

depth = 1 OU = Domain Control Validated, CN = www.WebSite.com

verify error:num = 38: cannot verify the first certificate`

However, the debugging approach is complete with the certificate chain that contains a single element. Lastly, it would help if you referenced the signing authorities in a chain trusted by Android, as shown below:

Certificate chain

1 s:/OU = Domain Control Validated/CN = www.WebSite.com

i:/O = Alpha/CN = AlphaSSL CA – G2

Certificate chain

1 s:/OU = Domain Control Validated/CN = www.WebSite.com

i:/O = Alpha/CN = AlphaSSL CA – G2

1 s:/O = Alpha/CN = AlphaSSL CA – G2

i:/C = BE/O = GlobalSign nv-sb/OU = Root CA/CN = Global Root CA

2 s:/C = BE/O = GlobalSign nv-sb/OU = Root CA/CN = Global Root CA

i:/C = BE/O = GlobalSign nv-sb/OU = Root CA/CN = Global Root CA

This code snippet completes the second debugging approach that obliterates the error and allows your processes.

– Testing the Domain on Kotlin

You can remove the error by testing the domain on SSL labs, which ensures all paths and locations are fully functional. You can learn more about this principle in the following script:

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()

.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 {

private fun getUnsafeOkHttpClient(): OkHttpClient.Builder =

try {

val trustAllCerts: Array <TrustManager> = arrayOf(

object : X509TrustManager {

@Throws (CertificateException:: class)

override fun checkClientTrusted (chain: Array < X509 Certificate?>?,

authType: String?) = Unit

@Throws (CertificateException:: class)

override fun checkServerTrusted (chain: Array < X509 Certificate?>?,

authType: String?) = Unit

override fun getAcceptedIssuers (): Array < X509 Certificate> = arrayOf()

}

}

This script is the last debugging approach covered in this guide. Lastly, you must update the build Gradle to complete the process.

Conclusion

The trust anchor for certification path Android error appears due to invalid or broken user certificates in the server configuration. Fortunately, this article explained the following critical points that help you remove the bug:

  • Your program can sometimes fail to recognize the certification paths from untrusted sources
  • We suggest recreating the error to help you troubleshoot the broken processes
  • You can quickly apply the debugging approaches to your certificates
  • Ensure all paths are functional before launching the processes
  • You can test the domains on Kotlin to debug the mistake

Experiencing certification path error is typical when your document has insecure anchors and certificates. Luckily, this guide taught several debugging approaches that clear your inconsistencies and bugs.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

  • Ошибка java runtime environment not found
  • Ошибка java net socket timeout
  • Ошибка java net connectexception connection refused no further information
  • Ошибка java net connect
  • Ошибка java lang unsatisfiedlinkerror