Glide - Javax.Net.Ssl.Sslhandshakeexception: Java.Security.Cert.Certpathvalidatorexception: Trust Anchor for Certification Path Not Found

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

The issue is about certificate follow this link -https://stackoverflow.com/a/39032433/4741746

This will bypass certificate and allow you to enter in system

see this link also -https://futurestud.io/tutorials/glide-module-example-accepting-self-signed-https-certificates

Create your custom GlideModule Class,OkHttpUrlLoader class and attach to you Glide as mention in above link

You have to put

<meta-data
android:name="io.futurestud.tutorials.glide.glidemodule.CustomImageSizeGlideModule"
android:value="GlideModule" />

Inside application tag of your AndroidMainifiest file https://github.com/fs-opensource/android-tutorials-glide/blob/master/app/src/main/AndroidManifest.xml

Https Images in Glide Library for Android

Upon inspecting with your image link in Glide, I found the error to be because of signing the server security with Self-signed certificate (making it HTTPS) and server configuration. The exact error would be:

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

See if this helps. https://stackoverflow.com/a/41114813/6720181

Glide V4 load https images

I am struggling near about 1 day but find solution, if you are using ssl certified link like https then you need to add two more dependency of glide so you have to add this

implementation 'com.github.bumptech.glide:annotations:4.5.0'
kapt 'com.github.bumptech.glide:compiler:4.5.0'

I am using kotlin thats why i added kapt you can use annotationProcessor

After that you need to create GlideModule in project, so here is the code for Glide V4

 @GlideModule
public class MyGlideModule extends AppGlideModule {

@Override
public void applyOptions(Context context, GlideBuilder builder) {
super.applyOptions(context, builder);
}

@Override
public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {
OkHttpClient okHttpClient= UnsafeOkHttpClient.getUnsafeOkHttpClient();
registry.replace(GlideUrl.class, InputStream.class, new OkHttpUrlLoader.Factory(okHttpClient));
}
}

here we are bypass the ssl so here is the UnsafeOkHttpClient class

    public class UnsafeOkHttpClient {

public static 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();

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;
}
});

OkHttpClient okHttpClient = builder.build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

after that you need two more class OkHttpUrlLoader and OkHttpStreamFetcher

you can copy past from Glide Link

After that final step which i am dont know thats why it will take one day so you need to build project and Glide will generate GlideApp class, so you need to use that GlideApp class to show image HTTPS
like this:

GlideApp.with(context).load(url).apply(RequestOptions.circleCropTransform()).into(imageView)

I think this is very help full for others which are suffering this typeof issues.
Keep Code :)

Glide not loading some Image URL

You need to download the certificate from the source domain. just open the SSL cert and drag and drop the image into your raw directory of your android project. rename and remove the extensions and ' . ' full stops.

my dependencies look like this

dependencies {
implementation fileTree( dir: 'libs', include: ['*.jar'] )

implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

// https://mvnrepository.com/artifact/com.koushikdutta.ion/ion
implementation group: 'com.koushikdutta.ion', name: 'ion', version: '2.2.0'

}

I'm using Ion 2.2.0 and works well with your not working images.

import java.io.InputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class MainActivity extends AppCompatActivity {

private ImageView img;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

img = findViewById(R.id.ntImg);

try {

CertificateFactory cf = CertificateFactory.getInstance("X.509");
// cert file stored in \app\src\main\res\raw
InputStream caInput = getResources().openRawResource(R.raw.freshtocook);

Certificate ca = cf.generateCertificate(caInput);
caInput.close();

KeyStore keyStore = KeyStore.getInstance("BKS");
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);

String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);

TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(tmf.getTrustManagers());

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, wrappedTrustManagers, null);

AsyncSSLSocketMiddleware sslMiddleWare = Ion.getDefault(MainActivity.this).getHttpClient().getSSLSocketMiddleware();
sslMiddleWare.setTrustManagers(wrappedTrustManagers);
sslMiddleWare.setHostnameVerifier(getHostnameVerifier());
sslMiddleWare.setSSLContext(sslContext);

Ion.with(MainActivity.this)
.load("https://freshtocook.in/uploads/banner/47a16ffc2fc5935dccd37574083c6201.jpg")
.asBitmap()
.setCallback(new FutureCallback<Bitmap>() {
@Override
public void onCompleted(Exception e, Bitmap bitmap) {
img.setImageBitmap(bitmap);
}
});

} catch (Exception e) {

}

}

private HostnameVerifier getHostnameVerifier() {
return new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
// or the following:
// HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
// return hv.verify("www.yourserver.com", session);
}
};
}

private TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers) {
final X509TrustManager originalTrustManager = (X509TrustManager) trustManagers[0];
return new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return originalTrustManager.getAcceptedIssuers();
}

public void checkClientTrusted(X509Certificate[] certs, String authType) {
try {
if (certs != null && certs.length > 0) {
certs[0].checkValidity();
} else {
originalTrustManager.checkClientTrusted(certs, authType);
}
} catch (CertificateException e) {
Log.w("checkClientTrusted", e.toString());
}
}

public void checkServerTrusted(X509Certificate[] certs, String authType) {
try {
if (certs != null && certs.length > 0) {
certs[0].checkValidity();
} else {
originalTrustManager.checkServerTrusted(certs, authType);
}
} catch (CertificateException e) {
Log.w("checkServerTrusted", e.toString());
}
}
}
};
}
}

for further support, my manifest looks like this

    <application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

Sample Image
drag and drop the certificate from here. Click the lock icon > view the certificate > drag and drop it to your raw folder. and remember to rename and don't leave any parts other than the name.

Sample Image

Trust Anchor not found for Android SSL Connection

The solution of @Chrispix is dangerous! Trusting all certificates allows anybody to do a man in the middle attack! Just send ANY certificate to the client and it will accept it!

Add your certificate(s) to a custom trust manager like described in this post: Trusting all certificates using HttpClient over HTTPS

Although it is a bit more complex to establish a secure connection with a custom certificate, it will bring you the wanted ssl encryption security without the danger of man in the middle attack!



Related Topics



Leave a reply



Submit