Home > Java > javaTutorial > How to Set Custom Certificate Trust for Specific SSL Connections in Java?

How to Set Custom Certificate Trust for Specific SSL Connections in Java?

Susan Sarandon
Release: 2024-12-18 13:48:14
Original
836 people have browsed it

How to Set Custom Certificate Trust for Specific SSL Connections in Java?

Setting Custom Certificate Trust for Targeted Connections

Problem Statement

Integrating an external module into an application requires accessing an SSL-secured website using a self-signed certificate. The existing code fails due to trust issues with the certificate. The challenge is to enable the application to accept this self-signed certificate only for this specific connection, without compromising trust for other connections or modifying the system-wide certificate store.

Optimal Solution

To selectively trust a self-signed certificate for a specific connection, create a custom SSLSocket factory and set it on the HttpsURLConnection before establishing the connection:

...
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setSSLSocketFactory(sslFactory);
conn.setMethod("POST");
...
Copy after login

Creating the SSLSocket Factory

To create the SSLSocket factory, initialize it as follows:

/* Load the keyStore that includes self-signed cert as a "trusted" entry. */
KeyStore keyStore = ... 
TrustManagerFactory tmf = 
  TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
sslFactory = ctx.getSocketFactory();
Copy after login

Loading the Key Store

Load the key store containing the self-signed certificate as a "trusted entry":

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(trustStore, trustStorePassword);
trustStore.close();
Copy after login

Alternative Key Store Loading Method

Alternatively, use keytool to import the PEM format certificate into a key store:

keytool -import -file selfsigned.pem -alias server -keystore server.jks
Copy after login

The above is the detailed content of How to Set Custom Certificate Trust for Specific SSL Connections in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template