in my application I am trying to do a HTTPS POST request to my server.
However, I keep getting SSLHandshakeException — Chain chain validation failed, all the time. I tried to send a request using POSTMAN and I got a response from the server. What can be causing this error when I try to send the request from the application?
Here a code snippet where I try to send the post request:
public static JSONObject getDataLibConfiguration(Context context) throws HttpRequestException {
int statusCode = 0;
JSONObject commonInformation;
HttpsURLConnection connection = null;
try {
commonInformation = ConfigurationProcessor.getCommonInformation(context);
if (commonInformation == null) {
return null;
}
URL url = new URL(BuildConfig.SERVER_CONFIG_URL);
if (BuildConfig.DEBUG) {
LogUtils.d(TAG, "url = " + url.getPath());
}
connection = getHttpsConnection(url);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Content-Encoding", "gzip");
byte[] gzipped = HttpUtils.gzip(commonInformation.toString());
cos = new CountingOutputStream(connection.getOutputStream()); //<-- This is where I get the exception
cos.write(gzipped);
cos.flush();
statusCode = connection.getResponseCode();
// More code her
}
private static HttpsURLConnection getHttpsConnection(URL url) throws IOException, GeneralSecurityException {
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
MatchDomainTrustManager myTrustManager = new MatchDomainTrustManager(url.getHost());
TrustManager[] tms = new TrustManager[]{myTrustManager};
sslContext.init(null, tms, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
connection.setSSLSocketFactory(sslSocketFactory);
} catch (AssertionError ex) {
if (BuildConfig.DEBUG) {
LogFileUtils.e(TAG, "Exception in getHttpsConnection: " + ex.getMessage());
}
LogUtils.e(TAG, "Exception: " + ex.toString());
}
return connection;
}
asked Nov 12, 2018 at 15:25
2
In my case it was wrong date on phone.
Fixing date resolved an issue
answered Aug 1, 2019 at 8:05
VadimVadim
3,5152 gold badges16 silver badges22 bronze badges
5
The problem was that the certificate was expired.
answered Nov 14, 2018 at 10:11
KeselmeKeselme
3,4197 gold badges32 silver badges61 bronze badges
5
If you’re using an emulated device it may solve the problem if you just ‘Cold Boot’ it.
Sometimes the date on those things can get stuck if you let them run for some time, which results in this expired-certificate-problem.
answered Aug 28, 2020 at 7:45
0
In my case, I fetch this issue on Android Emulator.
When I clear emulator cache has resolved the issue.
answered Nov 10, 2021 at 9:48
0
My date and time were correct, but I didn’t have «Use Network Provided Time checked» in my system settings.
I fixed this issue by going to Settings > Date and Time > Check «Use network-provided time» and also check «Use network-provided time zone».
Then this error went away.
answered Feb 15, 2021 at 21:03
zetatlaszetatlas
2802 silver badges6 bronze badges
2
In my case, the issue was with the phone date. So please check it, set to automatic.
answered May 21, 2022 at 9:53
Hayk MkrtchyanHayk Mkrtchyan
2,5453 gold badges17 silver badges52 bronze badges
public static void trustEveryone() {
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
public boolean verify(String hostname, SSLSession session) {
return true;
}});
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new X509TrustManager(){
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
context.getSocketFactory());
} catch (Exception e) { // should never happen
e.printStackTrace();
}
}
or check system date of your device — I had this Exception when I tried to connect with wrong date!..
answered May 24, 2019 at 12:30
1
If anyone come across this issue pertaining to specific device, then the reason should be because of incorrect date set in the device.
answered Aug 17, 2020 at 13:41
0
I fixed this error by resetting my emulator date and time. My server is working fine just I changed the date and time of my emulator as current server time zone.
answered Nov 3, 2021 at 6:59
@Yash Bhardwaj in the comment on @Vadim answer said that the problem was in Glide framework. I faced the same problem: Https requests to server using Ktor framework were all successful, but when Glide tried to load image from the same server, it faced the SSLHandshakeException
.
To solve this issue you should look here: Solve Glide SSLHandshakeException.
To make a deal with @GlideModule
annotation you should import kapt
plugin and add these dependencies into your app build.gradle
:
implementation 'com.github.bumptech.glide:okhttp3-integration:4.11.0'
kapt 'com.github.bumptech.glide:compiler:4.12.0'
answered Oct 17, 2021 at 10:08
If you use android emulator, you can wipe data and run again, it works
answered Jul 17, 2022 at 13:32
in my application I am trying to do a HTTPS POST request to my server.
However, I keep getting SSLHandshakeException — Chain chain validation failed, all the time. I tried to send a request using POSTMAN and I got a response from the server. What can be causing this error when I try to send the request from the application?
Here a code snippet where I try to send the post request:
public static JSONObject getDataLibConfiguration(Context context) throws HttpRequestException {
int statusCode = 0;
JSONObject commonInformation;
HttpsURLConnection connection = null;
try {
commonInformation = ConfigurationProcessor.getCommonInformation(context);
if (commonInformation == null) {
return null;
}
URL url = new URL(BuildConfig.SERVER_CONFIG_URL);
if (BuildConfig.DEBUG) {
LogUtils.d(TAG, "url = " + url.getPath());
}
connection = getHttpsConnection(url);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Content-Encoding", "gzip");
byte[] gzipped = HttpUtils.gzip(commonInformation.toString());
cos = new CountingOutputStream(connection.getOutputStream()); //<-- This is where I get the exception
cos.write(gzipped);
cos.flush();
statusCode = connection.getResponseCode();
// More code her
}
private static HttpsURLConnection getHttpsConnection(URL url) throws IOException, GeneralSecurityException {
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
MatchDomainTrustManager myTrustManager = new MatchDomainTrustManager(url.getHost());
TrustManager[] tms = new TrustManager[]{myTrustManager};
sslContext.init(null, tms, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
connection.setSSLSocketFactory(sslSocketFactory);
} catch (AssertionError ex) {
if (BuildConfig.DEBUG) {
LogFileUtils.e(TAG, "Exception in getHttpsConnection: " + ex.getMessage());
}
LogUtils.e(TAG, "Exception: " + ex.toString());
}
return connection;
}
asked Nov 12, 2018 at 15:25
2
In my case it was wrong date on phone.
Fixing date resolved an issue
answered Aug 1, 2019 at 8:05
VadimVadim
3,5152 gold badges16 silver badges22 bronze badges
5
The problem was that the certificate was expired.
answered Nov 14, 2018 at 10:11
KeselmeKeselme
3,4197 gold badges32 silver badges61 bronze badges
5
If you’re using an emulated device it may solve the problem if you just ‘Cold Boot’ it.
Sometimes the date on those things can get stuck if you let them run for some time, which results in this expired-certificate-problem.
answered Aug 28, 2020 at 7:45
0
In my case, I fetch this issue on Android Emulator.
When I clear emulator cache has resolved the issue.
answered Nov 10, 2021 at 9:48
0
My date and time were correct, but I didn’t have «Use Network Provided Time checked» in my system settings.
I fixed this issue by going to Settings > Date and Time > Check «Use network-provided time» and also check «Use network-provided time zone».
Then this error went away.
answered Feb 15, 2021 at 21:03
zetatlaszetatlas
2802 silver badges6 bronze badges
2
In my case, the issue was with the phone date. So please check it, set to automatic.
answered May 21, 2022 at 9:53
Hayk MkrtchyanHayk Mkrtchyan
2,5453 gold badges17 silver badges52 bronze badges
public static void trustEveryone() {
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
public boolean verify(String hostname, SSLSession session) {
return true;
}});
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[]{new X509TrustManager(){
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}}}, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
context.getSocketFactory());
} catch (Exception e) { // should never happen
e.printStackTrace();
}
}
or check system date of your device — I had this Exception when I tried to connect with wrong date!..
answered May 24, 2019 at 12:30
1
If anyone come across this issue pertaining to specific device, then the reason should be because of incorrect date set in the device.
answered Aug 17, 2020 at 13:41
0
I fixed this error by resetting my emulator date and time. My server is working fine just I changed the date and time of my emulator as current server time zone.
answered Nov 3, 2021 at 6:59
@Yash Bhardwaj in the comment on @Vadim answer said that the problem was in Glide framework. I faced the same problem: Https requests to server using Ktor framework were all successful, but when Glide tried to load image from the same server, it faced the SSLHandshakeException
.
To solve this issue you should look here: Solve Glide SSLHandshakeException.
To make a deal with @GlideModule
annotation you should import kapt
plugin and add these dependencies into your app build.gradle
:
implementation 'com.github.bumptech.glide:okhttp3-integration:4.11.0'
kapt 'com.github.bumptech.glide:compiler:4.12.0'
answered Oct 17, 2021 at 10:08
If you use android emulator, you can wipe data and run again, it works
answered Jul 17, 2022 at 13:32
У меня есть проект Android Studio, который вызывает веб-службу API. Когда сервисный код находится в dev, qa, prod и т.д. Никаких проблем с сертификатами нет, но при попытке открыть окно разработчиков веб-API для тестирования новой функции/исправления ошибки/и т.д. я получаю:
Нет ответа из-за ошибки:
javax.net.ssl.SSLHandshakeException: проверка цепочки не удалась
на com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:361)
У меня был самозаверяющий сертификат, экспортированный с машины разработчиков сервисов БЕЗ закодированного DER ключа. Я упал на эмулятор, и он «установлен», но это не сработало.
Я взял тот же сертификат выше и скопировал на эмулируемую SD-карту. Затем устанавливается из настроек безопасности в эмуляторе. Тот же результат. Проверка цепочки не удалась.
Теперь мои знания по безопасности/сертификатам очень просты. Я думаю, что ошибка на самом деле описывает проблему. В самозаверяющем сертификате нет цепочки… но я могу ошибаться.
Независимо от того, как мне обойти это?
Я хочу иметь возможность запускать свой код Android и устанавливать флажки для разработчиков для тестирования/отладки и т.д.
Я прочитал этот пост только для того, чтобы иметь корпоративную среду, в которой я блокирую сайты для открытого SSL и т.д.
https://android.stackexchange.com/info/61540/self-signed-certificate-install-claims-success-but-android-acts-as-if-cert-isn
Я получаю доступ к сервису через WebView.
Ответ 1
Причиной этой проблемы может быть неправильная дата и время устройства
Ответ 2
Я получал
javax.net.ssl.SSLHandshakeException: Chain validation failed
и
java.security.cert.CertPathValidatorException: Response is unreliable: its validity interval is out-of-date
решение, которое работало для меня, заключалось в том, чтобы заставить холодную загрузку эмулятора через Диспетчер виртуальных устройств → Выпадающее меню Actions → Cold Boot Now
Ответ 3
Просто перезагрузка эмулятора решила эту ошибку.
Длительно нажмите кнопку выключения питания в меню эмулятора и выберите «Перезагрузка».
Ответ 4
холодная загрузка работала нормально для меня. Большое спасибо !!
Ответ 5
Я стер все данные с эмулятора и снова загрузил его, установил приложение и все работало. Но видел другое решение, я думаю, что теперь это может быть излишним.
Ответ 6
Я знаю, что это старый вопрос, но у меня была похожая проблема с совершенно другим решением.
Убедитесь, что ваш SSL не истек. После того, как я исправил эту проблему, я больше не получал ошибки «javax.net.ssl.SSLHandshakeException: Chain validation fail». У меня были другие проблемы, но это другая тема.
Это звучит как такое очевидное решение, но это то, на что нужно обратить внимание, и это не обязательно первое, что приходит на ум людям.
Я получил javax.net.ssl.SSLHandshakeException: Chain validation failed
, когда я пытаюсь подключиться к своему API-серверу, сертификат действителен в настоящее время, и в трассировке стека я получил Caused by: java.security.cert.CertPathValidatorException: Response is unreliable: its validity interval is out-of-date
, сертификат действителен, и он работает над iOS и на сайте проблема только в Android.
Я использую Retrofit, вот поколение clitent
fun generateClient(): OkHttpClient {
val client = OkHttpClient.Builder()
client.addInterceptor {
val request = it.request()
val url = request.url().newBuilder()
.build()
val newRequest = it.request().newBuilder().url(url).build()
it.proceed(newRequest)
}
client.connectTimeout(10, TimeUnit.SECONDS)
client.readTimeout(30, TimeUnit.SECONDS)
return client.build()
}
И полный след это
javax.net.ssl.SSLHandshakeException: Chain validation failed
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:361)
at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:302)
at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:270)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:162)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at es.app.webservice.WebService$Companion$generateClient$1.intercept(WebService.kt:67)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:180)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:91)
at es.app.bd.cacheDb.databseRepositories.SplashActivityRepository$getVersions$1.invoke(SplashActivityRepository.kt:28)
at es.app.bd.cacheDb.databseRepositories.SplashActivityRepository$getVersions$1.invoke(SplashActivityRepository.kt:17)
at kotlin.concurrent.ThreadsKt$thread$thread$1.run(Thread.kt:30)
Caused by: java.security.cert.CertificateException: Chain validation failed
at com.android.org.conscrypt.TrustManagerImpl.verifyChain(TrustManagerImpl.java:788)
at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:612)
at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:633)
at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:678)
at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:499)
at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:422)
at com.android.org.conscrypt.TrustManagerImpl.getTrustedChainForServer(TrustManagerImpl.java:343)
at android.security.net.config.NetworkSecurityTrustManager.checkServerTrusted(NetworkSecurityTrustManager.java:94)
at android.security.net.config.RootTrustManager.checkServerTrusted(RootTrustManager.java:88)
at com.android.org.conscrypt.Platform.checkServerTrusted(Platform.java:203)
at com.android.org.conscrypt.OpenSSLSocketImpl.verifyCertificateChain(OpenSSLSocketImpl.java:607)
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:357)
at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.java:302)
at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.java:270)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:162)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at es.app.bd.cacheDb.webservice.WebService$Companion$generateClient$1.intercept(WebService.kt:67)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall.execute(RealCall.java:77)
at retrofit2.OkHttpCall.execute(OkHttpCall.java:180)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall.execute(ExecutorCallAdapterFactory.java:91)
at es.app.bd.cacheDb.databseRepositories.SplashActivityRepository$getVersions$1.invoke(SplashActivityRepository.kt:28)
at es.app.bd.cacheDb.databseRepositories.SplashActivityRepository$getVersions$1.invoke(SplashActivityRepository.kt:17)
at kotlin.concurrent.ThreadsKt$thread$thread$1.run(Thread.kt:30)
Caused by: java.security.cert.CertPathValidatorException: Response is unreliable: its validity interval is out-of-date
E/AndroidRuntime: at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:133)
at sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:225)
at sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:143)
at sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:79)
at com.android.org.conscrypt.DelegatingCertPathValidator.engineValidate(DelegatingCertPathValidator.java:44)
at java.security.cert.CertPathValidator.validate(CertPathValidator.java:301)
at com.android.org.conscrypt.TrustManagerImpl.verifyChain(TrustManagerImpl.java:784)
... 39 more
Caused by: java.security.cert.CertPathValidatorException: Response is unreliable: its validity interval is out-of-date
at sun.security.provider.certpath.OCSPResponse.verify(OCSPResponse.java:619)
at sun.security.provider.certpath.RevocationChecker.checkOCSP(RevocationChecker.java:709)
at sun.security.provider.certpath.RevocationChecker.check(RevocationChecker.java:363)
at sun.security.provider.certpath.RevocationChecker.check(RevocationChecker.java:337)
at sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:125)
... 45 more
Suppressed: java.security.cert.CertPathValidatorException: Could not determine revocation status
at sun.security.provider.certpath.RevocationChecker.buildToNewKey(RevocationChecker.java:1092)
at sun.security.provider.certpath.RevocationChecker.verifyWithSeparateSigningKey(RevocationChecker.java:910)
at sun.security.provider.certpath.RevocationChecker.checkCRLs(RevocationChecker.java:577)
at sun.security.provider.certpath.RevocationChecker.checkCRLs(RevocationChecker.java:465)
at sun.security.provider.certpath.RevocationChecker.check(RevocationChecker.java:394)
... 47 more
Обновление 1: если я захожу на веб-страницу из Chrome на телефоне, она работает, но приложение все еще не работает.
2 ответа
Лучший ответ
Глядя на строку Suppressed: java.security.cert.CertPathValidatorException: Could not determine revocation status
, можно предположить, что сбой происходит на этапе проверки отзыва, который основан на протоколе OCSP.
Здесь может произойти то, что ваше устройство не подключено к Интернету и не может связаться с сервером авторизации, чтобы проверить действительность вашего сертификата (это только предположение).
Если вы не хотите, чтобы ваше приложение имело доступ к серверу авторизации, вы должны активировать «OCSP stappling» на вашем сервере. Это означает, что ваш сервер будет отправлять квитанцию проверки OCSP, а также сертификат.
2
Caroline
20 Фев 2019 в 11:49
В моем случае достаточно было просто установить правильное системное время на устройстве («Настройки»> «Система»> «Дата и время»> «Автоматическая дата и время»).
4
Vit Khudenko
24 Июл 2019 в 10:15