建立基于SSL的java socket安全连接
1、Server端代码片段:
public void server() { String type = "TLS";//类型 String keyf = "..\\srvstore";//key文件路径 String trustf = "..\\clitrust";//信任证书库 String pass = "123456";//密码 int port = 8888;//端口 try { //初始化上下文 SSLContext ctx = SSLContext.getInstance(type); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); KeyStore ks = KeyStore.getInstance("JKS"); KeyStore tks = KeyStore.getInstance("JKS"); //载入keystore ks.load(new FileInputStream(keyf), pass.toCharArray()); tks.load(new FileInputStream(trustf), pass.toCharArray()); kmf.init(ks, pass.toCharArray()); tmf.init(tks); ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); SSLServerSocket sslServerSocket = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket(port); sslServerSocket.setNeedClientAuth(true);//客户端认证 Socket socket = sslServerSocket.accept(); //多线程处理... } catch (Exception e) { e.printStackTrace(); } }
|
2、Client端代码片段:
public void client() { String host = "localhost"; int port = 8888; String keyf = "..\\clistore"; String trustf = "..\\srvtrust"; String pass = "12345678"; try { SSLContext ctx = SSLContext.getInstance("TLS"); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); KeyStore ks = KeyStore.getInstance("JKS"); KeyStore tks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(keyf), pass.toCharArray()); tks.load(new FileInputStream(trustf), pass.toCharArray()); kmf.init(ks, pass.toCharArray()); tmf.init(tks); ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); SSLSocketFactory ssf = ctx.getSocketFactory(); socket = (SSLSocket) ssf.createSocket(host, port); socket.startHandshake(); //socket IO处理...
} catch (Exception e) { e.printStackTrace(); return; } }
|
3、生成数字证书:
服务端应用"服务端私钥"和"客户端公钥"与客户端通讯;
客户端应用"客户端私钥"和"服务端公钥"与服务端通讯。
1、用JDK的keytool生成密钥store
keytool -genkey -alias serverkey -keystore srvstore
keytool -genkey -alias clientkey -keystore clistore
输入密码(12345678)和相应的证书信息(姓名为DNS或邮件名,国家代码CN)
2、从srvstore中导出证书(bin format)
keytool -export -alias serverkey -file srvcert.crt -keystore srvstore
keytool -export -alias clientkey -file clicert.crt -keystore clistore
输入刚才上面设置的密码
3、将证书导到公钥中
keytool -import -alias servertrust -file srvcert.crt -keystore srvtrust
keytool -import -alias clienttrust -file clicert.crt -keystore clitrust
输入公钥的密码(12345678)
//发布的时候乱码真是一件郁闷的事:(
阅读(3688) | 评论(0) | 转发(0) |