我使用Sockets
开发了一个聊天服务器和客户端,一切都很好,直到我在网上看到普通的Socket
通信容易受到攻击。谷歌搜索了一段时间后,我遇到了this page,它显示了一个示例SSLServerSocket
和SSLSocket
实现(下面的代码)。
如果我按照以下代码中的步骤操作,我想知道我的服务器和客户端之间的通信是否安全。
服务器代码
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
}
}
}
}
}
答案 0 :(得分:1)
您应该通过HandshakeCompletionListener或SSLSession获取对等证书,以验证您是否正在与您认为正在与之通话的主持人通话。除此之外,从安全角度来看,您的代码是可以的。
但是你也应该知道你不应该通过网络使用PrintWriter,因为它会吞下异常。