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

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

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号