question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to make REST POST request using CRT and Key file

See original GitHub issue

I have been trying to make rest calls using client certificate in my request but unable to do so due to this error message “javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target”

Below are the steps I have tried so far:

  1. I was provided with mycompany.pem and cert.key private files

  2. I have converted .pem and key file to Java mycompany.p12 file format

  3. Added mycompany.p12 to java keyStore

  4. Then I’ve executed following code ` KeyStore keyStore = null; SSLConfig config = null; String password = “changeit”;

     try {
         keyStore = KeyStore.getInstance("PKCS12");
         keyStore.load(
                 new FileInputStream("/mypath/mycompany.p12"),
                 password.toCharArray());
    
     } catch (Exception ex) {
         System.out.println("Error while loading keystore >>>>>>>>>");
         ex.printStackTrace();
     }
    
     if (keyStore != null) {
    
         org.apache.http.conn.ssl.SSLSocketFactory clientAuthFactory = new org.apache.http.conn.ssl.SSLSocketFactory(keyStore, password);
    
         // set the config in rest assured
         config = new SSLConfig().with().sslSocketFactory(clientAuthFactory).and().allowAllHostnames();
     }
     RestAssured.config = RestAssured.config().sslConfig(config);
    
     Response response = RestAssured.given().contentType(ContentType.JSON).body(MY_JSON_BODY).when().post("MY_URL").then().extract().response();
    
     System.out.println(response.statusCode());;`
    

When above code is executed, system throws this error message javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

  1. When I’ve sent a request using relaxedHTTPSValidation then the system does not throw the exception from previous steps however response status code returned as 400 instead 201.

  2. I have also tried disabling the SSLValidation using below code but it didn’t work either

` public static void disable() { try { SSLContext sslc = SSLContext.getInstance(“TLS”); TrustManager[] trustManagerArray = { new NullX509TrustManager() }; sslc.init(null, trustManagerArray, null); HttpsURLConnection.setDefaultSSLSocketFactory(sslc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(new NullHostnameVerifier()); } catch(Exception e) { e.printStackTrace(); } }

private static class NullX509TrustManager implements X509TrustManager {
    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        System.out.println();
    }
    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        System.out.println();
    }
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
}

private static class NullHostnameVerifier implements HostnameVerifier {
    public boolean verify(String hostname, SSLSession session) {
        return true;
    }
}

public static Boolean disableSSLValidation() throws Exception {
    final SSLContext sslContext = SSLContext.getInstance("TLS");

    sslContext.init(null, new TrustManager[]{new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }}, null);

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    return true;
}`
  1. I am able to make successful request using POSTMAN

Note: I have been trying to make this work for some time so any help would be highly appreciated Thanks,

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:9

github_iconTop GitHub Comments

2reactions
mmuntakim15commented, May 5, 2017

the above script worked, I had to add cer file to my keystore then it worked just fine.

thanks @pumano

0reactions
ZoricaMarkoviccommented, Jul 7, 2022

@conngbha Thank you for the posting your code here. I’m trying to do the same thing described in this PR: Make REST POST request using .cert and key file. I did the following:

  • add the certificate to cacerts using the command: keytool -import -trustcacerts -alias mdecert -file /Users/<user>/IdeaProjects/restassured-cert-example/example.cert.pem -keystore -cacerts

  • convert the key.pem file to .p12 file format using the command: openssl pkcs12 -export -nocerts -inkey example.key.pem -out newformatexample.key.p12

  • then tried your code - please see the code below: `String clientPassword = “pass”; // use Passphrase given by client/dev String clientCertificatePath =“localhost.example.com.key.p12”; String trustStorePath=System.getProperty(“java.home”)+“/lib/security/cacerts”; String trustStorePassword = “changeit”; // changeit is the default password

      //String trustStorePassword = "pass";  // changeit is the default password
      KeyStore clientStore = KeyStore.getInstance("PKCS12");
      clientStore.load(new FileInputStream(clientCertificatePath), clientPassword.toCharArray());
    
      KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      kmf.init(clientStore, clientPassword.toCharArray());
      KeyManager[] kms = kmf.getKeyManagers();
    
      KeyStore trustStore = KeyStore.getInstance("PKCS12");
      trustStore.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray());
    
      TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
      tmf.init(trustStore);
      TrustManager[] tms = tmf.getTrustManagers();
    
      SSLContext sslContext = null;
      sslContext = SSLContext.getInstance("TLS");
      sslContext.init(kms, tms, new SecureRandom());
    
      SSLSocketFactory lSchemeSocketFactory=null;
    
      lSchemeSocketFactory = new SSLSocketFactory(clientStore, clientPassword, trustStore);
      RestAssuredConfig reconfig = RestAssured.config().sslConfig(new SSLConfig().with().sslSocketFactory(lSchemeSocketFactory).and().allowAllHostnames()
              .keyStore(clientCertificatePath, "pass").keystoreType("PKCS12")
              .trustStore(trustStorePath, trustStorePassword).trustStoreType("PKCS12"));
      
      Response res= given().when().contentType("application/json")
                      .config(reconfig).relaxedHTTPSValidation()
              .get("someendpointurl");
    
      System.out.println(res.asString());`
    

But it also didn’t work.

Do you maybe have any idea what else I can try? Thanks in advance.

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to make HTTPS GET call with certificate in Rest-Assured ...
In my case using "relaxed HTTPs validation" fixed my problem: given().relaxedHTTPSValidation().when().post("https://my_server.com").
Read more >
REST Assured API Testing step by step tutorial to resolve ...
Based on viewers request, here is a updated video of same : https://www.youtube.com/watch?v=cekjYjl3utUREST Assured API Testing step by step ...
Read more >
Solve the dreadful certificate issues in Python requests module
Recently I have been working with the Python requests module to secure an API call using the server's certificate.
Read more >
Making Your First API Call Using Postman - ADP
Summary: Instructions on how to use Postman to make your first API call to ... Click Certificates and enter the Host, CRT file...
Read more >
How to issue a SSL/TLS certificate for a domain via REST API?
Issue a certificate: Create an SSL/TLS certificate using csr/key/cert files: # curl -k -X POST -H "X-API-Key: ce8b9a38-4410-.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found