20

I'm trying to establish a https connection using the server's .cer certificate file. I am able to manually get the certificate file using a browser and put it into the keystore using keytool. I can then access the keystore using java code, obtain the certificate i added to the keystore and connect to the server.

I now however want to implement even the process of getting the certificate file and adding it to my keystore using java code and without using keytool or browser to get certificate.

Can someone please tell me how to approach this and what I need to do?

Vishal
  • 549
  • 1
  • 4
  • 21
Rohit
  • 523
  • 2
  • 6
  • 25
  • What purpose does this serve? I can't imagine why you would want to do this. – erickson Apr 09 '12 at 22:54
  • I am trying to verify the form contents in my internal server before posting the client's request back to hp's server. This I believe would prevent any browser based payment tampering and my server could do all the expected checks instead of having hp's website do it. For doing so however I need to get the server's certificate using java code to perform the handshake. I do not want to manually download the certificate every time and put it in my keystore. I want the code to do that part automatically.. – Rohit Apr 11 '12 at 15:32
  • You shouldn't need the server certificate in your key store. If the server is configured correctly, all you need is the "root" of the server's certificate chain. – erickson Apr 12 '12 at 00:31
  • Unfortunately since I am connecting to an external server I have no control over their configurations. – Rohit Apr 12 '12 at 13:03
  • You should realize that you are forfeiting the ability to authenticate the server by doing this. You don't know whether you are sending payment info to HP or to a scammer. Any legitimate payment processor will have correctly configured their service so that you can authenticate it. Otherwise, using TLS is completely pointless. – erickson Apr 12 '12 at 15:27

3 Answers3

16

Edit: This seems to do exactly what you want.

Using the following code it is possible to add a trust store during runtime.

import java.io.InputStream;
import java.security.KeyStore;

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

public class SSLClasspathTrustStoreLoader {
    public static void setTrustStore(String trustStore, String password) throws Exception {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509");
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream keystoreStream = SSLClasspathTrustStoreLoader.class.getResourceAsStream(trustStore);
        keystore.load(keystoreStream, password.toCharArray());
        trustManagerFactory.init(keystore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustManagers, null);
        SSLContext.setDefault(sc);
    }
}

I used this code to establish a secure LDAP connection with an active directory server.

This could also be usful, at the bottom there is a class, which is able to import a certificate during runtime.

Hexaholic
  • 3,299
  • 7
  • 30
  • 39
Sandro
  • 1,266
  • 2
  • 13
  • 25
1

I wrote small library ssl-utils-android to do so.

You can simply load any certificate by giving the filename from assets directory.

Usage:

OkHttpClient client = new OkHttpClient();
SSLContext sslContext = SslUtils.getSslContextForCertificateFile(context, "BPClass2RootCA-sha2.cer");
client.setSslSocketFactory(sslContext.getSocketFactory());
klimat
  • 24,711
  • 7
  • 63
  • 70
0

Just followed

https://docs.oracle.com/cd/E19509-01/820-3503/ggfgo/index.html https://www.sslshopper.com/article-most-common-java-keytool-keystore-commands.html

javac -cp .:/home/ec2-user/velu/*: QuickStart.java
java -cp .:/home/ec2-user/velu/*:  QuickStart


[ec2-user@ip-10-30-0-66 velu]$ ls
QuickStart.class  commons-codec-1.2.jar       input-payload.txt          logback-core-1.1.3.jar
QuickStart.java   commons-httpclient-3.1.jar  httpclient-4.5.jar  jdk-8u101-linux-x64.rpm    slf4j-api-1.7.12.jar
certificates      commons-logging-1.2.jar     httpcore-4.4.1.jar  logback-classic-1.1.3.jar



import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class QuickStart {

        public static void main(String[] args) throws Exception {
                System.setProperty("javax.net.ssl.keyStore", "/home/user/velu/certificates/myownOut.pkcs12");
                System.setProperty("javax.net.ssl.keyStorePassword", "password");

                System.setProperty("javax.net.ssl.trustStore", "/home/user/velu/certificates/myTrustStore");
                System.setProperty("javax.net.ssl.trustStorePassword", "password");

System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug");
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");

                CloseableHttpClient httpclient = HttpClients.createDefault();

                HttpClientParams params = new HttpClientParams();
                params.setConnectionManagerClass(MultiThreadedHttpConnectionManager.class);
                HttpClient client = new HttpClient(params);

                HttpMethod m = new PostMethod("https://velu.org:443/Services/com/Echo");

                m.setRequestHeader("content-type", "application/xml");
                //m.setRequestHeader("Accept", "application/xml");
//              m.setRequestHeader("SOAPAction", "Echo");
                try {

                        ((PostMethod) m).setRequestEntity(new StringRequestEntity(getFileContent(), "application/xml", "UTF-8"));
                        System.out.println("VELU EXCUTING");
                        client.executeMethod(m);
                        if (m.getStatusCode() == 200) {
                                System.out.println("VELU RECEIVED:" + m.getResponseBodyAsString());
                        }
                } catch (IOException e) {
                        System.out.println(e.toString());
                } finally {
                        m.releaseConnection();
                }

        }

        public static String getFileContent() {

                BufferedReader br = null;
                String fileContent = "";
                try {

                        br = new BufferedReader(new FileReader(
                                        "/home/user/velu/input-payload.txt")); // Note that this file format should be proper.
                        String sCurrentLine = "";
                        while ((sCurrentLine = br.readLine()) != null) {
                                fileContent += sCurrentLine;
                        }
                        System.out.println(fileContent);

                } catch (IOException e) {
                        e.printStackTrace();
                } finally {
                        try {
                                if (br != null)
                                        br.close();
                        } catch (IOException ex) {
                                ex.printStackTrace();
                        }
                }
                return fileContent;
        }
Kanagavelu Sugumar
  • 18,766
  • 20
  • 94
  • 101