1

I am trying to connect to a website that uses a self-signed certificate in Android Studio. I'm getting error

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

for the URL object that I call openStream() on.

Since my code is in a testing environment, I am looking for a solution to either disable cert checking altogether, or explicitly allow a cert.

I spent several hours yesterday looking for solutions, but every guide is several years old and uses depreciated HTTP libraries.

Keifer
  • 165
  • 1
  • 2
  • 11

2 Answers2

1

If your minSdkVersion is 24 or higher, or if you only need to be doing this testing on such devices, you can configure your self-signed certificate via network security configuration.

If your minSdkVersion is 17 or higher, you can use my backport of network security configuration, preferably with OkHttp.

Or, there are other recipes for using self-signed certificates with OkHttp.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0

In addition to the answer by @CommonsWare, if you target API 14 (ISC) or above you have an option to install additional trusted certificates on the device, outside of the application. The instructions can be found here.

Certificates installed using this method are used by all applications on the device.

On APIs 14-23, user installed certificate will be trusted by default. On API 24 (Nougat), however, handling of user added certificate changed and they are not trusted by default. In order to make user defined certificates trusted, add the following code to network config:

<network-security-config>  
      <base-config>  
            <trust-anchors>  
                <!-- Trust preinstalled CAs -->  
                <certificates src="system" />  
                <!-- Additionally trust user added CAs -->  
                <certificates src="user" />  
           </trust-anchors>  
      </base-config>  
 </network-security-config>

More information about changes in Nougat related to certificates handling can be found here.

Vasiliy
  • 16,221
  • 11
  • 71
  • 127
  • None of the suggested fixes seem to be working for me. Is my problem that the emulator itself is blocking the cert? I cannot find a way to add certificates in my Nexus 5 emulator. – Keifer Jun 01 '17 at 15:47
  • @Keifer, then I suggest you add more information to the question: emuletor type, OS version, what you tried and failed – Vasiliy Jun 01 '17 at 16:52
  • In my case (API 30), I've had to reference network security config from AndroidManifest.xml application tag like this: Google docs specifically mention that here: https://developer.android.com/training/articles/security-config#manifest – Tom Raganowicz Nov 13 '22 at 17:37