Java SSL 连接错误 - 密钥库格式无效

Java SSL connection error - Invalid keystore format

我正在创建一个服务器和客户端一体化聊天应用程序,我正在尝试切换到 SSL 连接。我创建了一个 keystore.jks 和一个证书文件 (.cer),但现在当程序尝试建立连接时,代理客户端抛出:

Caused by: java.io.IOException: Invalid keystore format

代码如下:

System.setProperty("javax.net.ssl.keyStore", "certificates/keystore.jks");
System.setProperty("javax.net.ssl.trustStore", "certificates/certificate.cer");
System.setProperty("javax.net.ssl.keyStorePassword", "password");

if (this.role == ConnectionRole.SERVER) {
    connectingAlert.getJFrame().setVisible(true);
    setupServer();
    do {
        Thread.sleep(10);
    } while (socket == null);
}

if (this.role == ConnectionRole.CLIENT) {
    connectingAlert.getJFrame().setVisible(true);
    setupClient(targetIP);
}

private void setupServer() throws IOException {
    SSLServerSocketFactory sslSrvFact = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    serverSocket = (SSLServerSocket) sslSrvFact.createServerSocket(8080, 1);
    socket = (SSLSocket) serverSocket.accept();
    setupStreams();
}

private void setupClient(String IPAddress) throws IOException {
    SSLSocketFactory sslFact = (SSLSocketFactory) SSLSocketFactory.getDefault();
    socket = (SSLSocket) sslFact.createSocket("localhost", 8080);
    setupStreams();
}

private void setupStreams() throws IOException {
    dataOut = new ObjectOutputStream(socket.getOutputStream());
    dataIn = new ObjectInputStream(socket.getInputStream());
    chatInterface = ChatInterface.getInstance();
}
System.setProperty("javax.net.ssl.trustStore", "certificates/certificate.cer");

问题就在这里。 .cer 文件不是信任库。您需要使用 -trustcacerts 选项通过 keytool 将其导入到真正的 Java 信任库中。

但是根本不清楚您为什么要使用信任库。您是否希望拥有自签名证书的同行将它们发送给您?大多数情况下,您应该只使用 Java 附带的信任库,根本不要设置 javax.net.ssl.trustStore