How to insert a keystore certificate only at runtime from a class?

I have an application that should connect to a web service https.

Webservice offers a zip file containing the following 3 files: * .crt, * .csr, * .key

Question: can I put them in classpathapplications jarand then upload the certificate only at startup (possibly in my own repository / trust store, which is created on the fly)?

Or do I need to call them in java keystoreon each machine before I can use the client of my application?

My preferred way would be to not install them in the local java storage, but load them on the go during application startup.

+4
source share
1 answer

I found this to be really possible, also from classpath:

//pass a p12 or pfx file (file may be on classpath also)
public void initSSL(String keyStoreFile, String pass) {
        InputStream keyStoreStream = this.getClass().getClassLoader().getResourceAsStream(keyStoreFile);          

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            KeyStore keyStore = KeyStore.getInstance("PKCS12");

            keyStore.load(keyStoreStream, keyPassword.toCharArray());
            kmf.init(keyStore, keyPassword.toCharArray());

             KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            // init the trust manager factory by read certificates
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(trustStore);

            // 3. init the SSLContext using kmf and tmf above
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
            SSLContext.setDefault(sslContext);
}
+5
source

All Articles