Reputation: 11
I am using two-way authentication of my client-server socket implementation. Code of my server where I'm loading keystore and truststore looks that :
private void createSSLServerSocketFactory() {
try {
InputStream keyStoreInputStream = new FileInputStream(KEYSTORE_PATH);
InputStream trustStoreInputStream = new FileInputStream(TRUSTSTORE_PATH);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(keyStoreInputStream, KEYSTORE_PASSWORD.toCharArray());
keyStoreInputStream.close();
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, KEYSTORE_PASSWORD.toCharArray());
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(trustStoreInputStream, TRUSTSTORE_PASSWORD.toCharArray());
trustStoreInputStream.close();
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
factory = sslContext.getServerSocketFactory();
} catch (IOException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
and function run in Thread :
public void run() {
try {
createSSLServerSocketFactory();
SSLServerSocket ss = (SSLServerSocket) factory.createServerSocket(port);
while (true) {
SSLSocket s = (SSLSocket) ss.accept();
s.setNeedClientAuth(true);
SSLSession sslSession = s.getSession();
X509Certificate x509Certificate = sslSession.getPeerCertificateChain()[0];
String username = x509Certificate.getSubjectDN().getName().split("CN=")[1].split(",")[0];
x509Certificate.checkValidity();
....
}
}
But I would like to change my trustore on server sometimes, but I wouldn't stop server when I do this. How can I do this? Exchange trustore.jks
during server?
Upvotes: 1
Views: 37
Reputation: 11
We have done something similar for a different purpose some time back. Read the trust store file on application startup and load the values in trust store to a map. Keep that map it in memory. You should also note the timestamp of that file. Now, you use those values you hold in the map for your authentication. You should also have a periodic check to see if the timestamp of trust store file on disk got changed. If file is changed, reload it to your map. You can have a daemon thread in background to do all this for you. Hope this helps,Thanks.
Upvotes: 1