Skip to content

Instantly share code, notes, and snippets.

@skempken
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skempken/9953049 to your computer and use it in GitHub Desktop.
Save skempken/9953049 to your computer and use it in GitHub Desktop.
Java class that initializes a HttpClient using X.509-certificate-based client authentication.
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
/**
* Initializes a HttpClient using X.509-certificate-based client authentication.
* @author Sebastian Kempken
*
*/
public class SslHttpUtil {
private static final KeyManager[] getKeyManagersFromKeyStore(KeyStore keyStore, char[] password) throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException
{
final KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keyStore, password);
final KeyManager[] kms = kmfactory.getKeyManagers();
return kms;
}
public static final HttpClient createSslHttpClient(KeyStore keyStore, char[] password) {
try
{
SSLContext sslcontext = SSLContext.getInstance("TLS");
final KeyManager[] km = getKeyManagersFromKeyStore(keyStore, password);
sslcontext.init(km, null, null);
SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslcontext);
Scheme https = new Scheme("https", sslSocketFactory, 443);
Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(http);
schemeRegistry.register(https);
final HttpParams params = new BasicHttpParams();
ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);
return new DefaultHttpClient(cm, params);
}
catch(Exception exception)
{
throw new RuntimeException("Error initializing HttpClient", exception);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment