1

I have a pfx certificate which I installed in Windows certificate store and I am able to attach that in https rest call using C#.

Now I need to do the same thing using Java. I read that .pfx certificate has private key along with one or more certificates.

I am getting the following error: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target.

Things I have tried in Java

  1. I directly took the certificate from Windows store using KeyStore ks = KeyStore.getInstance("Windows-MY", "SunMSCAPI") and created a SSLContext which i used in HTTPS call

  2. I imported the certificate from Windows store as .cer file and read it from the code as a file and attached it https call

  3. I read the .pfx file from code and attached it to the call.

  4. I have added the certificate to cacerts file of Java-Home (C:/Work/certi/jre1.8.0_91/lib/security/cacerts) using KeyTool.

The complete Java code is as below.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Enumeration;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;

import javax.net.ssl.TrustManagerFactory;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.conn.ssl.NoopHostnameVerifier;


public class TestElk {

public static void main(String[] args) throws ClientProtocolException, IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnrecoverableKeyException, NoSuchProviderException {
        
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    Certificate certificate = certificateFactory.generateCertificate(new FileInputStream(new File("C:/Work/certi/jre1.8.0_91/lib/security/elkcert.cer")));//exported certificate

    /* KeyStore ks = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
    ks.load(null,null);
    
    Enumeration enumeration = ks.aliases();     
    while(enumeration.hasMoreElements()) {            
        String alias = (String)enumeration.nextElement();
        System.out.println("alias name: " + alias);        }
    
    Certificate[] certificate = ks.getCertificateChain("alias");
     */
    
    // Create TrustStore        
    KeyStore trustStoreContainingTheCertificate =     KeyStore.getInstance(KeyStore.getDefaultType());
    trustStoreContainingTheCertificate.load(null, null);

    trustStoreContainingTheCertificate.setCertificateEntry("cert", certificate);

    // Create SSLContext
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStoreContainingTheCertificate);


    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null,trustManagerFactory.getTrustManagers(),new SecureRandom());
    SSLContext.setDefault(sslContext);
    
    HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;   
    
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    URL url = new URL("https://server-link");
    
    HttpsURLConnection con =    (HttpsURLConnection)url.openConnection();           
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
    con.setConnectTimeout(10000);
    con.setSSLSocketFactory(sslContext.getSocketFactory()); 
    con.connect();
    
    BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line+"\n");
    }
    br.close();
    System.out.println(sb.toString());
    //int s= con.getResponseCode();  }
Jeevika
  • 155
  • 1
  • 4
  • 18

1 Answers1

2

The following should work, given that you have imported the Issuing CA Cert (see comment below) to the cacerts file, a lot of help can be found in a different SO thread Here:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.conn.ssl.NoopHostnameVerifier;


public class TestElk {

public static void main(String[] args) throws ClientProtocolException, IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnrecoverableKeyException, NoSuchProviderException {

    
    KeyStore clientStore = KeyStore.getInstance("PKCS12");
    clientStore.load(new FileInputStream(new File("C:/path_to_pfx/mypfx.pfx")), "pfxPass".toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(clientStore, "pfxPass".toCharArray());
    KeyManager[] kms = kmf.getKeyManagers();
    
    // Assuming that you imported the CA Cert "Subject: CN=MBIIS CA, OU=MBIIS, O=DAIMLER, C=DE"
    // to your cacerts Store.
    KeyStore trustStore = KeyStore.getInstance("JKS");
    trustStore.load(new FileInputStream("cacerts"), "changeit".toCharArray());

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    TrustManager[] tms = tmf.getTrustManagers();

    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kms,tms,new SecureRandom());
    SSLContext.setDefault(sslContext);

    HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;   
    System.setProperty("https.proxyHost", "IP_OF_PROXY_HOST_GOES_HERE");
    System.setProperty("https.proxyPort", "PORT_NUMBER_GOES_HERE");
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

    URL url = new URL("https://server-link");

    HttpsURLConnection con =    (HttpsURLConnection)url.openConnection();           
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
    con.setConnectTimeout(10000);
    con.setSSLSocketFactory(sslContext.getSocketFactory()); 
    con.connect();

    BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line+"\n");
    }
    br.close();
    System.out.println(sb.toString());
    //int s= con.getResponseCode();
}

}
Jeroen Steenbeeke
  • 3,884
  • 5
  • 17
  • 26
Exception_al
  • 1,049
  • 1
  • 11
  • 21
  • 1
    " unable to find valid certification path to requested target" tells that the Root / Sub CA is not trusted. In your case, you don't trust the Root (MBIIS CA) which issued the Server Certificate for the Destination "CN=*.dvb.corpinter.net" ... – Exception_al Jan 17 '17 at 14:35
  • Update the log to your question , I can't access a link on your C: Drive :) – Exception_al Jan 17 '17 at 17:01
  • Add the error part only.... I would initiate chat but my reputation is not enough for it – Exception_al Jan 17 '17 at 17:08
  • In the event that "CN=MBIIS CA, OU=MBIIS, O=DAIMLER, C=CN" is a SubCA of "CN=MBIIS CA, OU=MBIIS, O=DAIMLER, C=DE", then your client keystore needs to deliver the entire chain ... When you export the pfx from your internet explorer, you can include the chain if I am not mistaken, check out https://www.digicert.com/images/code-signing/export/ie_code_signing_cert-3.jpg – Exception_al Jan 17 '17 at 22:07
  • I used actual .pfx certificate which i got in mail to create keymanager from clientstore in our program. It has only 1 certificate. Then from browser i am able to export using only first 3 options.. i.e .pfx export is disabled. :(. How do we know if certificate is a sub CA of another and then how to add then and deliver together. – Jeevika Jan 18 '17 at 04:06
  • Your initial issue is solved and what you have now is a new problem , it would be nice if you mark response as an answer. .. for further questions I suggest you use Google instead, for adding chain to a pfx : http://stackoverflow.com/questions/18787491/adding-certificate-chain-to-p12pfx-certificate – Exception_al Jan 18 '17 at 06:56