我正在使用客户端-服务器套接字实现的双向身份验证。我正在加载密钥库和信任库的服务器代码如下:
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();
}
}
和在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();
....
}
}
但我有时想在服务器上更改我的信任,但当我这样做时,我不会停止服务器。我该怎么做?是否在服务器期间交换trustore.jks
?
一段时间前,我们为了不同的目的做了类似的事情。在应用程序启动时读取信任存储文件,并将信任存储中的值加载到映射中。把那张地图记在记忆里。您还应该注意该文件的时间戳。现在,您可以使用映射中的那些值进行身份验证。您还应该定期检查磁盘上信任存储文件的时间戳是否已更改。若文件已更改,请将其重新加载到地图中。您可以在后台有一个守护进程线程来为您完成这一切。希望这能有所帮助,谢谢。