DelphiFAQ Home Search:
General :: Programming :: Java


Articles:

This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.

Featured Article

How to create SSL socket connection with a custom trusted key store

Question:

I dynamically add a trusted certificate to Tomcat's trustedKeyStore. How can I make them effective without restarting Tomcat? Basically, I want to force the JVM to re-read the list of trusted keys.

Answer:

You need to create your own custom SSLSocketFactory, which will use a customized SSLContext. In the example below, I created a custom SSLContext where I both specify the keystore and the trusted key store.
You may need to specify the custom trust manager only.

Replace
context.init(kms, tms, null);
with
context.init(null, tms, null);

  String TRUSTED_KEYSTORE = "/etc/ssl/trusted_keys.keystore";
   String trustStorePassword = "secret";
         
         
 protected KeyManager[] getKeyManagers() throws IOException, GeneralSecurityException {
                 
         String alg=KeyManagerFactory.getDefaultAlgorithm();
         KeyManagerFactory kmFact=KeyManagerFactory.getInstance(alg);
                 
         FileInputStream fis=new FileInputStream(TRUSTED_KEYSTORE);
         KeyStore ks=KeyStore.getInstance("jks");
         ks.load(fis, trustStorePassword.toCharArray());
         fis.close();
         
         kmFact.init(ks, trustStorePassword.toCharArray());
         
         return kmFact.getKeyManagers();
 }
                         
                         
 protected TrustManager[] getTrustManagers() throws IOException, GeneralSecurityException {
                         
         String alg=TrustManagerFactory.getDefaultAlgorithm();
         TrustManagerFactory tmFact=TrustManagerFactory.getInstance(alg);
                         
         FileInputStream fis=new FileInputStream(TRUSTED_KEYSTORE);
         KeyStore ks=KeyStore.getInstance("jks");
         ks.load(fis, trustStorePassword.toCharArray());
         fis.close();
                                 
         tmFact.init(ks);
                          
         return tmFact.getTrustManagers();
 }
                         
                         
 protected SSLSocketFactory getSSLSocketFactory() throws IOException, GeneralSecurityException {
                 
         TrustManager[] tms=getTrustManagers();
                         
         KeyManager[] kms=getKeyManagers();
                 
         SSLContext context=SSLContext.getInstance("SSL");
         context.init(null, tms, null);
                  
         return context.getSocketFactory();
 }
 
 
 //
 // main code
 //
 
 SSLSocketFactory socketFactory = (SSLSocketFactory) getSSLSocketFactory();
 
 clientSocket = (SSLSocket) socketFactory.createSocket(IP_Address, 443);
 

Generated 0:01:45 on Nov 24, 2017