当前位置:首页 > 开发 > 互联网 > 正文

TLS java简单实现

发表于: 2014-12-14   作者:antlove   来源:转载   浏览:
摘要:   1. SSLServer.java package ssl; import java.io.FileInputStream; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.security.KeyStore; import

 

1. SSLServer.java

package ssl;

import java.io.FileInputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyStore;
import java.util.logging.Logger;

import javax.net.ServerSocketFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;

public class SSLServer {
	private String SERVER_KEY_STORE = "/D:/Projects/J2EE/JDK/src/ssl/keystore/server_ks";  
    private String SERVER_KEY_STORE_PASSWORD = "123123";  
    
    private Logger logger = Logger.getLogger(this.getClass().getName());
	
	private SSLServerSocket createSSLServerSocket() throws Exception{
		// whether enable the debug mode
	    System.setProperty("javax.net.debug", "ssl,handshake");  
		System.setProperty("javax.net.ssl.trustStore", SERVER_KEY_STORE);  
        SSLContext context = SSLContext.getInstance("TLS");  
          
        KeyStore ks = KeyStore.getInstance("jceks");  
        ks.load(new FileInputStream(SERVER_KEY_STORE), null);  
        KeyManagerFactory kf = KeyManagerFactory.getInstance("SunX509");  
        kf.init(ks, SERVER_KEY_STORE_PASSWORD.toCharArray());
        context.init(kf.getKeyManagers(), null, null);  
        
        ServerSocketFactory factory = context.getServerSocketFactory();  
        ServerSocket serverSocket = factory.createServerSocket(8443);  
        SSLServerSocket sslServerSocket =  (SSLServerSocket) serverSocket;
        // set whether need the client authentication
//        sslServerSocket.setNeedClientAuth(true); 
        return sslServerSocket;
	}
	
	private void start() throws Exception{
		SSLServerSocket sslServerSocket= createSSLServerSocket();
		
		while(true){
			try{
				Socket socket = sslServerSocket.accept();
				InputStream is = socket.getInputStream();
				byte[] bytes = new byte[Short.MAX_VALUE];
				int len = -1;
				
				while((len = is.read(bytes))>0){
					logger.info(new String(bytes,0,len));
					if(len<bytes.length){
						break;
					}
				}
				socket.getOutputStream().write("server balabala ... ".getBytes());
				socket.close();
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
    
	public static void main(String[] args)throws Exception {
		new SSLServer().start();
	}
}

 

2. SSLClient.java

package ssl;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.security.KeyStore;
import java.util.logging.Logger;

import javax.net.SocketFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;

public class SSLClient {
	private static String CLIENT_KEY_STORE = "/D:/Projects/J2EE/JDK/src/ssl/keystore/client_ks";  
	private static String CLIENT_KEY_STORE_PASSWORD = "456456";  
	
	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	private Socket createNonAuthenticationSocket()throws Exception{
		System.setProperty("javax.net.ssl.trustStore", CLIENT_KEY_STORE);  
        SocketFactory sf = SSLSocketFactory.getDefault();  
        Socket s = sf.createSocket("localhost", 8443);  
        return s;  
	}
	
	private Socket createAuthenticationSocket() throws Exception{
		System.setProperty("javax.net.ssl.trustStore", CLIENT_KEY_STORE);  
        SSLContext context = SSLContext.getInstance("TLS");  
        KeyStore ks = KeyStore.getInstance("jceks");  
        ks.load(new FileInputStream(CLIENT_KEY_STORE), null);  
        KeyManagerFactory kf = KeyManagerFactory.getInstance("SunX509");  
        kf.init(ks, CLIENT_KEY_STORE_PASSWORD.toCharArray());  
        context.init(kf.getKeyManagers(), null, null);  
          
        SocketFactory factory = context.getSocketFactory();  
        Socket s = factory.createSocket("localhost", 8443);  
        return s;  
	}
	
	private void connect()throws Exception{
	   Socket s = createNonAuthenticationSocket();  
//     Socket s = createAuthenticationSocket();  
 
       PrintWriter writer = new PrintWriter(s.getOutputStream());  
       BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));  
       writer.println("hello");  
       writer.flush();  
       logger.info(reader.readLine());  
       s.close();  
	}
	
	
    public static void main(String[] args) throws Exception {  
    	new SSLClient().connect();
    }  
}

 

PS : 解压 client_server_keystore.rar, 然后分别拷贝到指定的如下位置.

SERVER_KEY_STORE = "/D:/Projects/J2EE/JDK/src/ssl/keystore/server_ks",

CLIENT_KEY_STORE = "/D:/Projects/J2EE/JDK/src/ssl/keystore/client_ks".

然后分别运行SSLServer,SSLClient。

 

更过可参考如下:

Https(SSL/TLS)原理详解

SSL介绍与Java实例


 

TLS java简单实现

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
转载:http://blog.csdn.net/wangyangzhizhou/article/details/38406253 JSSE(Java 安全套接字扩展
Java网络编程系列: Java网络编程一:Java Socket简例 Java网络编程二:Java Secure(SSL/TLS) Socke
协议完成有: - 最小化完成了RFC821, RFC822, 简单的邮件发送协议,邮件格式化协议 - 最小化完成R
import java.util.Scanner; class Node { public String value; // 字母节点 public Node left, rig
Java SSL/TLS 安全通讯协议介绍 刘 进, 高级软件工程师 , IBM2013 年 5 月 23 日 简介 本文主要介绍
伴随着现代化通信系统的建立,人们利用数学理论找到了一些行之有效的方法来保证数字通信的安全。简
转自:http://www.blogjava.net/xcp/archive/2010/04/13/318125.html 摘要 :单点登录( SSO )的技
摘要 : 单点登录( SSO )的技术被越来越广泛地运用到各个领域的软件系统当中。本文从业务的角度分
在大一的时候,我对敲代码一直有着很深的反感,一直认为敲代码是一件枯燥无味的事情,每天甚至要在
摘要 :单点登录( SSO )的技术被越来越广泛地运用到各个领域的软件系统当中。本文从业务的角度分
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号