1

I need to perform a rest call by attaching the local ssl certificate.

I do not have any info about KeyStore. I just know there is a Certificate installed in my PC and I have to use the certificate based on details of certificate like "Serial number", "Issuer" etc which i can see in the certificate details in the personal certificate store.

I need to create SSLConnectionSocketFactory object which can be attached to rest call.

My question is how to create the SSLContext object?

  SSLContext sslContext;// How to create this object and pass it to sslSocketFactory.

  HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; 
  SSLConnectionSocketFactory sslSocketFactory = new  SSLConnectionSocketFactory(sslContext, hostnameVerifier); 

1 Answer 1

1

You can create the SSLContext instance using this code snippet.

// Load Certificate
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Certificate certificate = certificateFactory.generateCertificate(new FileInputStream(new File("CERTIFICATE_LOCATION")));

// Create TrustStore
KeyStore trustStoreContainingTheCertificate = KeyStore.getInstance("JKS");
trustStoreContainingTheCertificate.load(null, null);

trustStoreContainingTheCertificate.setCertificateEntry("ANY_CERTIFICATE_ALIAS", certificate);

// Create SSLContext
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStoreContainingTheCertificate);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
System.out.println(sslSocketFactory);
Sign up to request clarification or add additional context in comments.

2 Comments

How do I create the " trustStoreContainingTheCertificate"?
Can I get LayeredConnectionSocketFactory() of org.apache.http.conn.socket.LayeredConnectionSocketFactory instead of SSLSocketFactory at the end?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.