1

我正在使用我的客户端-服务器套接字实现的双向身份验证。我正在加载密钥库和信任库的服务器的代码如下所示:

    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在服务器期间交换?

4

1 回答 1

1

不久前,我们出于不同的目的做了类似的事情。在应用程序启动时读取信任库文件并将信任库中的值加载到映射中。将该地图保存在内存中。您还应该注意该文件的时间戳。现在,您使用地图中保存的那些值进行身份验证。您还应该定期检查磁盘上信任存储文件的时间戳是否已更改。如果文件已更改,请将其重新加载到您的地图中。您可以在后台拥有一个守护线程来为您完成所有这些工作。希望这会有所帮助,谢谢。

于 2018-12-11T12:19:17.513 回答