Thursday, January 18, 2018

Testing HTTPS Connections with Apache HttpClient - SSL Certificate


D:\>keytool -keypass secret -storepass secret -genkey -alias httpskey -keyalg RSA -keystore D:\https_keystore.jks
What is your first and last name?
  [Unknown]:  Nagaraju Gajula
What is the name of your organizational unit?
  [Unknown]:  RR
What is the name of your organization?
  [Unknown]:  Yas
What is the name of your City or Locality?
  [Unknown]:  Ban
What is the name of your State or Province?
 [Unknown]:  91
What is the two-letter country code for this unit?
  [Unknown]:  91
Is CN=Nagaraju Gajula, OU=RR, O=Yas, L=Ban, ST=91, C=91 correct?
  [no]:  yes


D:\>keytool -export -alias httpskey -keystore D:\https_keystore.jks -storepass secret -file server.cert
Certificate stored in file <server.cert>

D:\>keytool -import -v -trustcacerts -alias httpskey -keystore D:\client_truststore.jks -storepass secret -file server.cert
Owner: CN=Nagaraju Gajula, OU=RR, O=Yas, L=Ban, ST=91, C=91
Issuer: CN=Nagaraju Gajula, OU=RR, O=Yas, L=Ban, ST=91, C=91
Serial number: 4b3167d6
Valid from: Wed Dec 27 16:17:57 IST 2017 until: Tue Mar 27 16:17:57 IST 2018
Certificate fingerprints:
         MD5:  A4:64:C2:00:6D:04:48:21:C4:5D:02:78:EC:F5:E0:E5
         SHA1: AB:48:BE:2D:87:71:03:08:3C:09:FA:AE:B6:0D:0D:4A:D7:E0:60:FE
         SHA256: 00:EE:1C:71:36:1A:C7:69:24:C2:BC:54:E2:96:BD:FF:7C:87:02:87:8B:F4:72:97:11:39:C9:1B:D9:2E:50:29
         Signature algorithm name: SHA256withRSA
         Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: 0E 9A FF 86 9D 6B 34 60   82 AB B7 5E 35 90 71 0E  .....k4`...^5.q.
0010: 13 D3 FD 2D                                        ...-
]
]

Trust this certificate? [no]:  yes
Certificate was added to keystore
[Storing D:\client_truststore.jks]

D:\>

package com.mkyong.jersey;

import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.Before;
import org.junit.Test;

/**
* Tests connecting to a HTTPS server that does not require a client certificate.
*
* @author Ivan Krizsan
*/
public class HttpsNoClientCertificateTest {
    /* Constant(s): */
    /** URL which to send test-request to. */
    private final static String TEST_ENDPOINT_URL = "https://localhost:8443/App/api/get?name=nagaraju";
    /** Client truststore. */
    private static final String CLIENT_TRUSTSTORE = "client_truststore.jks";
    /** Client truststore password. */
    private static final String CLIENT_TRUSTSTORE_PASSWORD = "secret";

    /* Instance variable(s): */
    private static DefaultHttpClient mHttpClient;

    public  static void main(String[] args) throws Exception {
        mHttpClient = new DefaultHttpClient();
         FileInputStream instream = new FileInputStream(new File("D:/client_truststore.jks"));
         /* Load client truststore. */
         final KeyStore theClientTruststore = KeyStore.getInstance("JKS");
         theClientTruststore.load(instream,
             CLIENT_TRUSTSTORE_PASSWORD.toCharArray());

         /* Create a trust manager factory using the client truststore. */
         final TrustManagerFactory theTrustManagerFactory =
             TrustManagerFactory.getInstance(TrustManagerFactory
                 .getDefaultAlgorithm());
         theTrustManagerFactory.init(theClientTruststore);

         /*
          * Create a SSL context with a trust manager that uses the
          * client truststore.
          */
         final SSLContext theSslContext = SSLContext.getInstance("TLS");
         theSslContext.init(null, theTrustManagerFactory.getTrustManagers(),
             null);

         /*
          * Create a SSL socket factory that uses the client truststore SSL
          * context and that does not perform any kind of hostname verification.
          * IMPORTANT: Hostname verification should be performed in a
          * production environment!
          * To turn on hostname verification, change the
          * ALLOW_ALL_HOSTNAME_VERIFIER below to STRICT_HOSTNAME_VERIFIER.
          */
         final SSLSocketFactory theSslSocketFactory =
             new SSLSocketFactory(theSslContext,
                 SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

         /*
          * Register the SSL socket factory to be used with HTTPS connections
          * with the HTTP client.
          * A {@code Scheme} object is used to associate the protocol scheme,
          * such as HTTPS in this case, and a socket factory.
          */
         final Scheme theHttpsScheme =
             new Scheme("https", 443, theSslSocketFactory);
         mHttpClient.getConnectionManager().getSchemeRegistry().register(
             theHttpsScheme);
        HttpGet httpget = new HttpGet(TEST_ENDPOINT_URL);
        httpget.addHeader("test-header-name", "test-header-value");
        System.out.println("executing request" + httpget.getRequestLine());

               CloseableHttpResponse response = mHttpClient.execute(httpget);
               try {
                   HttpEntity entity = response.getEntity();

                   System.out.println("----------------------------------------");
                   System.out.println(response.getStatusLine());
                   if (entity != null) {
                       System.out.println("Response content length: " + entity.getContentLength());
                   }
                   String responseString = EntityUtils.toString(entity, "UTF-8");
                   System.out.println(responseString);
               } finally {
                   response.close();
               }
    }


}

No comments:

Post a Comment

Recent Post

Databricks Delta table merge Example

here's some sample code that demonstrates a merge operation on a Delta table using PySpark:   from pyspark.sql import SparkSession # cre...