Java HTTPS client certificate authentication

To perform HTTPS client certificate authentication in Java, you can use the HttpsURLConnection class and the SSLSocketFactory class.

Here is an example of how to set up client certificate authentication with the HttpsURLConnection class:

String urlString = "https://example.com/api";
URL url = new URL(urlString);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream("client.p12"), "password".toCharArray());

KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, "password".toCharArray());

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), null, null);

connection.setSSLSocketFactory(sslContext.getSocketFactory());

connection.setRequestMethod("GET");
connection.setDoInput(true);

InputStream inputStream = connection.getInputStream();
// read the response

In this example, the KeyStore class is used to load the client certificate from a PKCS12 file, the KeyManagerFactory class is used to create a key manager from the client certificate, and the SSLContext class is used to create an SSL context with the key manager. The setSSLSocketFactory() method of the HttpsURLConnection class is used to set the SSL socket factory with the SSL context.

I hope this helps. Let me know if you have any questions.