我使用openSSL为我的客户端和服务器创建了密钥和证书。这两个证书都由同一个CA签名,因此客户端和服务器可以相互信任。现在我需要在我的程序中使用这些证书才能实现双方身份验证,但我不知道如何在我当前的代码中“导入”它们。这是我到目前为止所做的。
服务器侧
import java.io.*;
import java.io.*;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import static java.lang.System.*;
public class SSlServer {
public static void main(String[] args) {
SSLSocket sslsocket=null;
try
{
SSLServerSocketFactory sslserversocketfactory =(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket sslserversocket =(SSLServerSocket) sslserversocketfactory.createServerSocket(5555);
while (true)
{
sslsocket = (SSLSocket) sslserversocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(sslsocket.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(sslsocket.getOutputStream()));
/* other stuff being done here */
/*............................*/
}
} catch (IOException ex) {
System.out.println("Error in socket");
} finally
{
if (sslsocket != null)
{
try {
in.close();
out.close();
sslsocket.close();
} catch (IOException ex) {
System.out.println("Exception in close");
}
}
}
}
客户端
import java.io.*;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class SSlClient {
public static void main(String[] args) {
try {
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("localhost", 5555);
/* other stuff being done here */
/*............................*/
sslsocket.close();
} catch (UnknownHostException ex) {
Logger.getLogger(SSlClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(SSlClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}