Java客户端/服务器SSL套接字聊天

时间:2014-10-17 17:34:38

标签: java sockets openssl client serversocket

好的朋友,所以我使用TCP客户端/服务器套接字创建了一个java聊天。 我创建服务器,然后我创建连接到服务器的客户端,以便他们可以通过服务器相互通信! 代码:服务器:

public ServerChat() throws Exception{
    ServerSocket soc=new ServerSocket(5217);


    while(true)
    {    
        Socket CSoc=soc.accept();        
        //and then the code for handling the messages, we don't need that 

    }
}

客户:

 Server soc=new Socket("127.0.0.1",5217);
Thread t=new Thread(this);
t.start();
//i Have ommited many parts of the code, but you know, i focus on the connection part of the problem!`

所以现在,我想使用SSL保护(所以我可以看到wireshark中的更改)。 我使用OpenSSL(它是我的配置所必需的)来创建根CA和设备证书。我将文件放在netbeans上的src文件夹中,并将代码复制到两个新类SSLServer和SSLClient,并对其进行了实验。 SSL部分!所以:

public SSLServer() throws Exception{
SSLContext sslContext=????//supposed to add the files somehow here? 
SSLServerSocketFactory factory=(SSLServerSocketFactory)slContext.getServerSocketFactory();
SSLServerSocket sslserversocket=(SSLServerSocket) factory.createServerSocket(1234);
while(true)
{   
SSLSocket sslsocket=(SSLSocket)sslserversocket.accept();                
}
}

客户也一样。所以我有点卡在SSLContext部分!我在这里阅读了许多帖子,但仍然...... SSLContext下面的部分是否正确?我如何在SSLContext中使用证书? 编辑:也许这会奏效吗? :

KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("keystoreFile"), "keystorePassword".toCharArray());

KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
kmf.init(ks, "keystorePassword".toCharArray());

TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); 
tmf.init(ks);

SSLContext sc = SSLContext.getInstance("TLS"); 
TrustManager[] trustManagers = tmf.getTrustManagers(); 
sc.init(kmf.getKeyManagers(), trustManagers, null); 

SSLServerSocketFactory ssf = sc.getServerSocketFactory(); 
SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(serverport);
SSLSocket c = (SSLSocket) s.accept();

1 个答案:

答案 0 :(得分:1)