티스토리 뷰

Retrofit을 이용해 http 통신을 하던 중 "java.security.cert.CertPathValidatorException: Trust anchor for certification path not found." 에러가 발생 하였다.

해당 에러는 https 인증서가 만료 되거나 인증되지 않은 인증서를 사용 한 경우 발생 한다.

아래와 같이 OkHttpClient 사용을 수정 하였다.


문제 발생 코드

OkHttpClient client = new OkHttpClient();

문제 해결 코드
해결 class를 하나 만들고 사용

public class TrustOkHttpClientUtil {

    public static OkHttpClient.Builder 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;
                }
            });
            return builder;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

OkHttpClient client = TrustOkHttpClientUtil.getUnsafeOkHttpClient().build();

 

댓글