Monday, 20 October 2014

Trusting certficates on the fly in java

   Below is the code snippet which helps you in trusting the https certificates on the fly in jave program,


 public Response trustCertificate(HttpsURLConnection conn,Method method,String body){
        Response response = new Response();
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                @Override
                public void checkClientTrusted( final X509Certificate[] chain, final String authType ) {
                }
                @Override
                public void checkServerTrusted( final X509Certificate[] chain, final String authType ) {
                }
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            } };
            // 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();
            // Tell the url connection object to use our socket factory which bypasses security checks
            ( (HttpsURLConnection) conn ).setSSLSocketFactory( sslSocketFactory );
            if(Method.PUT.equals(method) || Method.POST.equals(method)){
                conn.setDoOutput(true);
                final OutputStream os = conn.getOutputStream();
                os.write(body.getBytes());
                os.flush();
                os.close();
            }
           
           
            final InputStream input = conn.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader( input));

            String line;
            while ((line = rd.readLine()) != null)
            {
                response.body += line;
            }              
            rd.close();

            response.statusCode = conn.getResponseCode();
            conn.disconnect();
           
        } catch ( final Exception e ) {
            e.printStackTrace();
            response.exception = e.getMessage();
        }
        return response;
    }

No comments:

Post a Comment