3

I want to use a HttpAsyncClient using SSL and with Client authentication (in addition to Server auth).

I had some problems, but finally I found the right way. I show you how to do it:


Generate keystore from PEM (PEM -> PKCS#12 keystore -> JKS keystore)

Create PKCS12 keystore from private key and public certificate:

sudo openssl pkcs12 -export -name myservercert -in selfsigned.crt -inkey server.key -out keystore.p12

Convert PKCS12 keystore into a JKS keystore:

sudo keytool -importkeystore -destkeystore mykeystore.jks -srckeystore keystore.p12 -srcstoretype pkcs12 -alias myservercert

List the contents of the JKS keystore:

sudo keytool -list -v -keystore mykeystore.jks

Your local JVM should trust the server Certificate. If its self-signed, add it to the cacerts (trusted certificates list; its default password is 'changeit'):

sudo keytool -import -alias alias_serv_cert -file /var/tmp/CERT_SERVER.cert -keystore /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.25.x86_64/jre/lib/security/cacerts

Java code to generate the client and do the POST:

char[] keystorePass = "MY PASSWORD".toCharArray();

FileInputStream fis = null;

//Loading KEYSTORE in JKS format
KeyStore keyStorePci = KeyStore.getInstance(KeyStore.getDefaultType());
try {
fis = new FileInputStream(keystoreDirectory + keystoreFilename);
keyStorePci.load(fis, keystorePass);
} catch (Exception e) {
LOG.error("Error loading keystore: " + keystoreDirectory+ keystoreFilename);
} finally {
if (fis != null) {
fis.close();
}
}

//Setting JKS keystore in SSL Context (I do not reccomend pass a 3rd argument PrivateKeyStrategy!)
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStorePci, keystorePass).build();

//Creating Async HTTP client with SSL
CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setSSLContext(sslcontext).build();

//Executing POST method
try {

httpclient.start();
future = httpclient.execute(httppost, new MyCustomAsyncResultManager(transactionId, transactionToken));
HttpResponse response = future.get();
LOG.info("result: " + response.getStatusLine());

} finally {httpclient.close();}

I hope this could be helpful for you.

Carlos AG
  • 1,078
  • 1
  • 12
  • 16
  • 1
    thank you, but unfortunately this is not the correct place for posting it, consider writing a blog post about it :) – epoch Jan 17 '14 at 10:53
  • Nonetheless, finding this here was very helpful to me. Too bad stackoverflow doesn't have a knowledge share mode – PhaedrusTheGreek Sep 15 '17 at 18:57
  • The right way to share knowledge on Stack Overflow is to ask a question, post an answer to the same question and mark it as the accepted answer. – Chortos-2 Oct 22 '18 at 14:40

0 Answers0