Wednesday, March 16, 2016

How to embed a keystore certificate only during runtime from classpath?

Leave a Comment

I have an application that should connect to a https webservice.

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

Question: can I place them into the classpath of the application jar, and then load the cert only on startup (maybe in an own keystore/truststore that is is created on the fly)?

Or do I necessairly have to intall them into the java keystore on each machine, before I can use the my app client?

My preferred way would be to not having install them to the local java keystore, but load them on the fly during application startup.

1 Answers

Answers 1

I found it's actually 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); } 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment