0

我开发了一个聊天服务器和客户端Sockets,一切都很好,直到我在网上某处读到普通Socket通信容易受到攻击。谷歌搜索了一段时间后,我发现了这个页面,其中显示了一个示例SSLServerSocketSSLSocket实现(下面的代码)。

如果我按照以下代码中的步骤操作,我想知道我的服务器和客户端之间的通信是否安全。


服务器代码

class EchoServer {
  public static void main(String[] args) throws IOException {
    SSLServerSocket sslServerSocket = null;
    try {
      SSLServerSocketFactory sslServerSocketFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
      sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(9999);
      SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
      PrintWriter out = new PrintWriter(sslSocket.getOutputStream(),true);
      BufferedReader in = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
      String inputLine;
      while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
        out.println(inputLine);
      }
    } finally {
      if (sslServerSocket != null) {
        try {
          sslServerSocket.close();
        } catch (IOException x) {
          // handle error
        }
      }
    }
  }
}


客户代码

class EchoClient {
  public static void main(String[] args) throws IOException {
    SSLSocket sslSocket = null;
    try {
      SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
      sslSocket = (SSLSocket) sslSocketFactory.createSocket("localhost", 9999);
      PrintWriter out = new PrintWriter(sslSocket.getOutputStream(), true);
      BufferedReader in = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
      BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
      String userInput;
      while ((userInput = stdIn.readLine()) != null) {
        out.println(userInput);
        System.out.println(in.readLine());
      }
    } finally {
      if (sslSocket != null) {
        try {
          sslSocket.close();
        } catch (IOException x) {
          // handle error
        }
      }
    }
  }
}
4

1 回答 1

1

您应该通过 HandshakeCompletionListener 或 SSLSession 获取对等证书,以验证您正在与您认为正在与之交谈的主机交谈。除此之外,从安全的角度来看,您的代码是可以的。

但是,您还应该知道,您不应该在网络上使用 PrintWriter,因为它会吞下异常。

于 2014-07-12T03:03:20.700 回答