使用附加的代码SSLSocket通信是否安全



我使用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
        }
      }
    }
  }
}

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

然而,你也应该意识到你不应该在网络上使用printwwriter,因为它会吞噬异常。

相关内容

  • 没有找到相关文章

最新更新