Monday, 13 November 2017

javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated ???

If you are getting javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated when you are calling any API in server to server call.

Step 1:
Download the bouncy castle jars according to your Java version using below URL
https://www.bouncycastle.org/latest_releases.html

Step 2: Copy downloaded jars (bcpkix-jdk15on-1.50.jar, bcprov-jdk15on-1.50.jar) into your JRE ext directory.
Example - If you are installed java in C drive
C:\Java-JDK-1.6.0.45\Java\jdk1.6.0_45\jre\lib\ext\

Step 3: Open java.security file available in below path if you are installed java in C drive

C:\pavan\Java-JDK-1.6.0.45\Java\jdk1.6.0_45\jre\lib\security\java.security

add the below command end of the file java.security.
security.provider.2=org.bouncycastle.jce.provider.BouncyCastleProvider

Step 4: 
Use below method to overcome the same while creating the HttpClient object.

Create the HttpClient object using below code and call the API you will get result 100%!!!

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
......
private static HttpClient getHttpClient() {

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        sslContext.init(null,
                new TrustManager[]{new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {

                        return null;
                    }

                    public void checkClientTrusted(
                            X509Certificate[] certs, String authType) {

                    }

                    public void checkServerTrusted(
                            X509Certificate[] certs, String authType) {

                    }
                }}, new SecureRandom());

        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);



        HttpClient httpClient = HttpClientBuilder.create().setSSLSocketFactory(socketFactory).build();

        return httpClient;

    } catch (Exception e) {
        e.printStackTrace();
        return HttpClientBuilder.create().build();
    }
}

No comments:

Post a Comment