Send request with SSL/TLS Certificate

What is an SSL Certificate?

SSL stands for Secure Sockets Layer and, in short, it’s the standard technology for keeping an internet connection secure and safeguarding any sensitive data that is being sent between two systems, preventing criminals from reading and modifying any information transferred, including potential personal details.

SSL encrypts and ensures the authenticity of the whole connection, including the requested method and URL. A GET is just as well protected as a POST.

When SSL works as intended, an eavesdropper can only see what IP address is connecting to what IP address (and on what port, but it’s usually 443), at what time, and how much. If there are multiple virtual hosts on the same machine, the attacker cannot know which one you are contacting (however, the eavesdropper may see your DNS requests just before the HTTPS request and take a plausible guess). All this information is also authenticated: an active attacker cannot play man-in-the-middle and modify the data in transit.

a man-in-the-middle attack (MITM) is an attack where the attacker secretly relays and possibly alters the communication between two parties who believe they are directly communicating with each other. One example of man-in-the-middle attacks is active eavesdropping, in which the attacker makes independent connections with the victims and relays messages between them to make them believe they are talking directly to each other over a private connection, when in fact the entire conversation is controlled by the attacker. The attacker must be able to intercept all relevant messages passing between the two victims and inject new ones. This is straightforward in many circumstances; for example, an attacker within reception range of an unencrypted wireless access point (Wi-Fi) could insert himself as a man-in-the-middle.

Public Key and Private Keys

Public keys and private keys are part of a general structure we call PKI – Public Key Infrastructure. The SSL and TLS protocols, which are globally used to secure not only websites, but also emails and web applications, are based on this structure. So we might as well say that there are thousands and thousands of public and private keys in operation right now around the world!

In the case of SSL, one key – the public key – is used to encrypt data; only the corresponding private key can decrypt it.

 

For example, if Bob wants to send sensitive data to Alice, and wants to be sure that only Alice may be able to read it, he will encrypt the data with Alice’s Public Key. Only Alice has access to her corresponding Private Key and as a result is the only person with the capability of decrypting the encrypted data back into its original form.

public-key-encryption

 

As only Alice has access to her Private Key, it is possible that only Alice can decrypt the encrypted data. Even if someone else gains access to the encrypted data, it will remain confidential as they should not have access to Alice’s Private Key.

 

Send request to server with certificate :

First import the .cert file to your JVM cacerts.

Certificate looks like :

-----BEGIN CERTIFICATE-----
MIIFUTCCBDmgAwIBAgIHK4FgDiVqczANBgkqhkiG9w0BAQUFADCByjELMAkGA1UE
BhMCVVMxEDAOBgNVBAgTB0FyaXpvbmExEzARBgNVBAcTClNjb3R0c2RhbGUxGjAY
...
RLJKd+SjxhLMD2pznKxC/Ztkkcoxaw9u0zVPOPrUtsE/X68Vmv6AEHJ+lWnUaWlf
zLpfMEvelFPYH4NT9mV5wuQ1Pgurf/ydBhPizc0uOCvd6UddJS5rPfVWnuFkgQOk
WmD+yvuojwsL38LPbtrC8SZgPKT3grnLwKu18nm3UN2isuciKPF2spNEFnmCUWDc
MMicbud3twMSO6Zbm3lx6CToNFzP
-----END CERTIFICATE-----

Import it using following command.

 

keytool -import -alias alias_name-file mycert.cer -keystore /java_home/jre/lib/security/cacerts-storepass changeit

Verify by checking if your certificate is in cacerts:

 

keytool -list -v -keystore keystore.jks

Then in your code:


        try {

//your jvm cacerts location
System.setProperty("javax.net.ssl.trustStore", "C:\\Program Files\\Java\\jdk1.8.0_131\\jre\\lib\\security\\cacerts");

//your cacets password
        System.setProperty("javax.net.ssl.trustStorePassword", "changeit");

        String version = System.getProperty("java.version");
        System.out.println("java version " + version);

        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream("E://mykeystore.jks"), "password".toCharArray());
        Enumeration & amp;lt;String & amp;gt;
        en = ks.aliases();
        int n = 0;
        PrivateKey privKey = null;
        Certificate certificate = null;
        Certificate[] certificates = null;
        String alias = "";
        while (en.hasMoreElements()) {
            String aliasKey = en.nextElement();
            System.out.println("aliaskey " + aliasKey);

            alias = aliasKey;

            privKey = (PrivateKey) ks.getKey(aliasKey, "password".toCharArray());
            System.out.println("privKey " + privKey);
            certificate = ks.getCertificate(aliasKey);
            System.out.println("certificate " + certificate);
            certificates = ks.getCertificateChain(aliasKey);
            System.out.println("certificates " + certificates);
            System.out.println("Provider " + ks.getProvider().getName());

            if (privKey != null & amp;amp; & amp;amp;
            alias.equals("alias_name")
            
                ) {
try {
                    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
                    kmf.init(ks, "password".toCharArray());
                    SSLContext sc = SSLContext.getInstance("TLS");
                    sc.init(kmf.getKeyManagers(), null, null);

                    SSLContext sslContext = null;
                    sslContext = SSLContext.getInstance("TLS");
                    sslContext.init(kmf.getKeyManagers(), null, null);

                    String url = "https://example.com";
                    URL urlObj = new URL(url);

                    HttpsURLConnection conn = (HttpsURLConnection) urlObj.openConnection();
                    if (conn instanceof HttpsURLConnection) {
                        ((HttpsURLConnection) conn).setSSLSocketFactory(sslContext.getSocketFactory());
                    }

                    conn.setReadTimeout(10000);
                    conn.setConnectTimeout(15000);
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/xml");
                    conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
                    conn.setDoInput(true);
                    conn.setDoOutput(true);

                    String urlOrder = "https://nabiltest.compassplus.com:8444/Exec";
                    URL urlObjOrder = new URL(urlOrder);

                    HttpsURLConnection connn = (HttpsURLConnection) urlObjOrder.openConnection();
                    if (connn instanceof HttpsURLConnection) {
                        ((HttpsURLConnection) connn).setSSLSocketFactory(sslContext.getSocketFactory());
                    }

                    connn.setReadTimeout(10000);
                    connn.setConnectTimeout(15000);
                    connn.setRequestMethod("POST");
                    connn.setRequestProperty("Content-Type", "application/xml");
                    connn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
                    connn.setDoInput(true);
                    connn.setDoOutput(true);

                    String payload = "data to send";

                    OutputStream output = new BufferedOutputStream(conn.getOutputStream());
                    output.write(payload.getBytes());

                    output.flush();
                    int responseCode = conn.getResponseCode();
                    System.out.println("Response code : " + responseCode);

                    String response = "";
                    if (responseCode == HttpsURLConnection.HTTP_OK || responseCode == HttpsURLConnection.HTTP_CREATED) {
                        String line;
                        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        while ((line = br.readLine()) != null) {
                            response += line;
                        }
                    } else if (responseCode & amp;gt;
                     = 400 & amp;amp; & amp;amp;responseCode & amp;lt;500
                    
                        ) {
String line;
                        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
                        while ((line = br.readLine()) != null) {
                            response += line;
                        }
                    }else {
response = "";
}

                    System.out.println("Result : " + response);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }
    catch (Exception e

    
        ) {
e.printStackTrace();
    }