Loading TrustStore and KeyStore from InputStream
suggest changepublic class TrustLoader {
public static void main(String args[]) {
try {
// Classpath resource /ssl/rpgrenadesClient.jks. The leading slash
// makes the path absolute from the classpath root.
InputStream stream = TrustLoader.class.getResourceAsStream("/ssl/rpgrenadesClient.jks");
//Both trustStores and keyStores are represented by the KeyStore object
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
//The password for the trustStore
char[] trustStorePassword = "password".toCharArray();
//This loads the trust store into the object
trustStore.load(stream, trustStorePassword);
//This is defining the SSLContext so the trust store will be used
//Getting default SSLContext to edit.
SSLContext context = SSLContext.getInstance("SSL");
// TrustManagers hold trust stores, more than one can be added
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
//Adds the truststore to the factory
factory.init(trustStore);
//This is passed to the SSLContext init method
TrustManager[] managers = factory.getTrustManagers();
context.init(null, managers, null);
//Sets our new SSLContext to be used.
SSLContext.setDefault(context);
} catch (KeyStoreException | IOException | NoSuchAlgorithmException
| CertificateException | KeyManagementException ex) {
//Handle error
ex.printStackTrace();
}
}
}
Initiating a KeyStore works the same, except replace any word Trust in an object name with Key. Additionally, the KeyManager[] array must be passed to the first argument of SSLContext.init. That is SSLContext.init(keyManagers, trustManagers, null).
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents