5

I have a file with the '.pfx' extension and a password to this certificate.

What I need to do is to send a simple GET request to a webservice and read the response body.

I need to implement a method similar to this:

String getHttpResponse(String url, String certificateFile, String passwordToCertificate){
    ...
}

I also tried converting the certificate to a format "with no password" using openssl:

Convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM:
openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes

So the alternate implementaion of the my method could be:

String getHttpResponse(String url, String certificateFile){
    ...
}

I would really appreciate your help, I spent half a day googling for it, but I haven't found an example that would help me, it seems I have problems with undestanding some basic assumptions around SSL and stuff.

Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145
dstronczak
  • 2,406
  • 4
  • 28
  • 41

2 Answers2

9

I finally found a good solution (without creating custom SSL context):

String getHttpResponseWithSSL(String url) throws Exception {
    //default truststore parameters
    System.setProperty("javax.net.ssl.trustStore", "/usr/lib/jvm/java-6-openjdk/jre/lib/securitycacerts");
    System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    System.setProperty("javax.net.ssl.trustStoreType", "JKS");

    //my certificate and password
    System.setProperty("javax.net.ssl.keyStore", "mycert.pfx");
    System.setProperty("javax.net.ssl.keyStorePassword", "mypass");
    System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");


    HttpClient httpclient = new HttpClient();

    GetMethod method = new GetMethod();
    method.setPath(url);

    int statusCode = httpclient.executeMethod(method);
    System.out.println("Status: " + statusCode);

    method.releaseConnection();

    return method.getResponseBodyAsString();
}
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
dstronczak
  • 2,406
  • 4
  • 28
  • 41
  • 1
    This is good in my case. However - what if I needed to change the settings in the runtime? Do you think setting System.setProperty again would be very wrong? – dstronczak Jun 12 '12 at 15:01
  • It's not that it would be "wrong", but more likely that it wouldn't work. – Bruno Jun 12 '12 at 15:08
1

This question should have your answer:

HTTPClient-1.4.2: Explanation needed for Custom SSL Context Example

You need to use httpclient to create the request and then use a key manager.

Community
  • 1
  • 1
plasma147
  • 2,191
  • 21
  • 35
  • I tried doing it this way, however I am not sure what file should I use as the "trustStore"... – dstronczak Jun 11 '12 at 08:12
  • According to [this] (http://docs.oracle.com/javase/6/docs/api/java/security/KeyStore.html#load%28java.io.InputStream,%20char[]%29) it can be null to create an empty keystore. – plasma147 Jun 11 '12 at 13:12