Search code examples
javaruntimekeystoretruststoresystem-properties

Recursively change system property at runtime in java


I am having a question and searching for an example for changing system property at runtime in java. In other words , I am having a standalone library which will load System.setProperty("javax.net.ssl.trustStore", trustStorePath) where the value of trustStorePath will change according to condition. If condition changes then I need to change the value of trustStorePath and need to set System Property.

But the story is when I set the value for very first time, it stores the value and use it even if I change the value of trustStorePath and again set system property. The change did not reflect.

So , How can I do the same. Below is the sample code snippet for the same .

        if (getFile(keyStorePath).exists()  && isChanged ) {
                System.setProperty("javax.net.ssl.keyStore", keyStorePath);
                System.setProperty("javax.net.ssl.keyStoreType", "JKS");
                System.setProperty("javax.net.ssl.keyStorePassword", Pwd);
        }else if (getFile(testMerchantKeyStorePath).exists() ) {
            System.setProperty("javax.net.ssl.keyStore", testMerchantKeyStorePath);
                System.setProperty("javax.net.ssl.keyStoreType", "JKS");
                System.setProperty("javax.net.ssl.keyStorePassword",Pwd);

    }

Solution

  • Sounds like you want to use a dynamic trust store. You could do this before you open any connection:

        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(new FileInputStream(new File("Your_New_Trust_Store_Path")), "password".toCharArray());
    
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ts);
    
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);
    
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    
        // Open Connection .... etc. ....
    

    You could do this each time your trustStorePath changes.