Java SSL/TLS Socket實現


通信端無需向對方證明自己的身份,則稱該端處於“客戶模式”,否則稱其處於“服務器模式”,無論是客戶端還是服務器端,都可處於“客戶模式”或者“服務器模式”

 

首先生成服務器端認證證書,使用java自帶的keytool工具:

其中:

-genkey:生成一對非對稱密鑰

-keyalg:加密算法

-keystore:證書存放路徑

-alias:密鑰對別名,該別名是公開的

相同的方式,生成客戶端認證證書,不過命名為client_rsa.key,別名為clientkey

使用jdk1.5,唯一需要引入的包為log4j-1.2.14.jar

客戶端認證:

package com.test.client.auth;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.Properties;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import com.test.server.config.Configuration;

public class Auth {
	private static SSLContext sslContext;
	
	public static SSLContext getSSLContext() throws Exception{
		Properties p = Configuration.getConfig();
		String protocol = p.getProperty("protocol");
		String sCertificateFile = p.getProperty("serverCertificateFile");
		String sCertificatePwd = p.getProperty("serverCertificatePwd");
		String sMainPwd = p.getProperty("serverMainPwd");
		String cCertificateFile = p.getProperty("clientCertificateFile");
		String cCertificatePwd = p.getProperty("clientCertificatePwd");
		String cMainPwd = p.getProperty("clientMainPwd");
		
		//KeyStore class is used to save certificate.
		char[] c_pwd = sCertificatePwd.toCharArray();
		KeyStore keyStore = KeyStore.getInstance("JKS");  
		keyStore.load(new FileInputStream(sCertificateFile), c_pwd);  
			
		//TrustManagerFactory class is used to create TrustManager class.
		TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509"); 
		char[] m_pwd = sMainPwd.toCharArray();
		trustManagerFactory.init(keyStore); 
		//TrustManager class is used to decide weather to trust the certificate 
		//or not. 
		TrustManager[] tms = trustManagerFactory.getTrustManagers();
		
		KeyManager[] kms = null;
		if(Configuration.getConfig().getProperty("authority").equals("2")){	
			//KeyStore class is used to save certificate.
			c_pwd = cCertificatePwd.toCharArray();
			keyStore = KeyStore.getInstance("JKS");  
			keyStore.load(new FileInputStream(cCertificateFile), c_pwd);  
			
			//KeyManagerFactory class is used to create KeyManager class.
			KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); 
			m_pwd = cMainPwd.toCharArray();
			keyManagerFactory.init(keyStore, m_pwd); 
			//KeyManager class is used to choose a certificate 
			//to prove the identity of the client side. 
			 kms = keyManagerFactory.getKeyManagers();
		}
		
		//SSLContext class is used to set all the properties about secure communication.
		//Such as protocol type and so on.
		sslContext = SSLContext.getInstance(protocol);
		sslContext.init(kms, tms, null);  
		
		return sslContext;
	}
}

客戶端主程序:

package com.test.client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Properties;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

import org.apache.log4j.Logger;

import com.test.client.auth.Auth;
import com.test.server.config.Configuration;
import com.test.tools.SocketIO;

public class Client {
	static Logger logger = Logger.getLogger(Client.class);
	private SSLContext sslContext;
	private int port = 10000;
	private String host = "127.0.0.1";
	private SSLSocket socket;
	private Properties p;
	
	public Client(){
		try {
			p = Configuration.getConfig();
			Integer authority = Integer.valueOf(p.getProperty("authority"));
			
			sslContext = Auth.getSSLContext();
			SSLSocketFactory factory = (SSLSocketFactory) sslContext.getSocketFactory();  
			socket = (SSLSocket)factory.createSocket(); 
			String[] pwdsuits = socket.getSupportedCipherSuites();
			socket.setEnabledCipherSuites(pwdsuits);//socket可以使用所有支持的加密套件
			if(authority.intValue() == 2){
				socket.setUseClientMode(false);
				socket.setNeedClientAuth(true);
			}else{
				socket.setUseClientMode(true);
				socket.setWantClientAuth(true);
			}
			
			SocketAddress address = new InetSocketAddress(host, port);
			socket.connect(address, 0);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("socket establish failed!");
		}
	}
	
	public void request(){
		try{
			String encoding = p.getProperty("socketStreamEncoding");
			
			DataOutputStream output = SocketIO.getDataOutput(socket);
			String user = "name";
			byte[] bytes = user.getBytes(encoding);
			short length = (short)bytes.length;
			short pwd = (short)123;
			
			
			output.writeShort(length);
			output.write(bytes);
			output.writeShort(pwd);
			
			DataInputStream input = SocketIO.getDataInput(socket);
			length = input.readShort();
			bytes = new byte[length];
			input.read(bytes);
			
			logger.info("request result:"+new String(bytes,encoding));
		}catch(Exception e){
			e.printStackTrace();
			logger.error("request error");
		}finally{
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args){
		Client client = new Client();
		client.request();
	}
}
服務器端認證:

package com.test.server.auth;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.Properties;

import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import com.test.server.config.Configuration;

public class Auth {
	private static SSLContext sslContext;
	
	public static SSLContext getSSLContext() throws Exception{
		Properties p = Configuration.getConfig();
		String protocol = p.getProperty("protocol");
		String sCertificateFile = p.getProperty("serverCertificateFile");
		String sCertificatePwd = p.getProperty("serverCertificatePwd");
		String sMainPwd = p.getProperty("serverMainPwd");
		String cCertificateFile = p.getProperty("clientCertificateFile");
		String cCertificatePwd = p.getProperty("clientCertificatePwd");
		String cMainPwd = p.getProperty("clientMainPwd");
			
		//KeyStore class is used to save certificate.
		char[] c_pwd = sCertificatePwd.toCharArray();
		KeyStore keyStore = KeyStore.getInstance("JKS");  
		keyStore.load(new FileInputStream(sCertificateFile), c_pwd);  
		
		//KeyManagerFactory class is used to create KeyManager class.
		KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509"); 
		char[] m_pwd = sMainPwd.toCharArray();
		keyManagerFactory.init(keyStore, m_pwd); 
		//KeyManager class is used to choose a certificate 
		//to prove the identity of the server side. 
		KeyManager[] kms = keyManagerFactory.getKeyManagers();
		
		TrustManager[] tms = null;
		if(Configuration.getConfig().getProperty("authority").equals("2")){
			//KeyStore class is used to save certificate.
			c_pwd = cCertificatePwd.toCharArray();
			keyStore = KeyStore.getInstance("JKS");  
			keyStore.load(new FileInputStream(cCertificateFile), c_pwd);  
			
			//TrustManagerFactory class is used to create TrustManager class.
			TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509"); 
			m_pwd = cMainPwd.toCharArray();
			trustManagerFactory.init(keyStore); 
			//TrustManager class is used to decide weather to trust the certificate 
			//or not. 
			tms = trustManagerFactory.getTrustManagers();
		}
		
		//SSLContext class is used to set all the properties about secure communication.
		//Such as protocol type and so on.
		sslContext = SSLContext.getInstance(protocol);
		sslContext.init(kms, tms, null);  
		
		return sslContext;
	}
}

服務器端主程序:

package com.test.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;

import org.apache.log4j.Logger;

import com.test.server.auth.Auth;
import com.test.server.business.Job;
import com.test.server.config.Configuration;

public class Server {
	static Logger logger = Logger.getLogger(Server.class);
	private SSLContext sslContext;
	private SSLServerSocketFactory sslServerSocketFactory;
	private SSLServerSocket sslServerSocket;
	private final Executor executor;
	
	public Server() throws Exception{
		Properties p = Configuration.getConfig();
		Integer serverListenPort = Integer.valueOf(p.getProperty("serverListenPort"));
		Integer serverThreadPoolSize = Integer.valueOf(p.getProperty("serverThreadPoolSize"));
		Integer serverRequestQueueSize = Integer.valueOf(p.getProperty("serverRequestQueueSize"));
		Integer authority = Integer.valueOf(p.getProperty("authority"));
		
		executor = Executors.newFixedThreadPool(serverThreadPoolSize);
		
		sslContext = Auth.getSSLContext();
		sslServerSocketFactory = sslContext.getServerSocketFactory();  
		//Just create a TCP connection.SSL shake hand does not begin.
		//The first time either side(server or client) try to get a socket input stream 
		//or output stream will case the SSL shake hand begin. 
		sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(); 
		String[] pwdsuits = sslServerSocket.getSupportedCipherSuites();
		sslServerSocket.setEnabledCipherSuites(pwdsuits);
		//Use client mode.Must prove its identity to the client side.
		//Client mode is the default mode.
		sslServerSocket.setUseClientMode(false);
		if(authority.intValue() == 2){
			//The communication will stop if the client side doesn't show its identity.
			sslServerSocket.setNeedClientAuth(true);
		}else{
			//The communication will go on although the client side doesn't show its identity.
			sslServerSocket.setWantClientAuth(true);
		}

		sslServerSocket.setReuseAddress(true);
		sslServerSocket.setReceiveBufferSize(128*1024);
		sslServerSocket.setPerformancePreferences(3, 2, 1);
		sslServerSocket.bind(new InetSocketAddress(serverListenPort),serverRequestQueueSize);
			
		logger.info("Server start up!");
		logger.info("server port is:"+serverListenPort);
	}

	private void service(){		
		while(true){
			SSLSocket socket = null;
			try{
				logger.debug("Wait for client request!");
				socket = (SSLSocket)sslServerSocket.accept();
				logger.debug("Get client request!");
				
				Runnable job = new Job(socket);
				executor.execute(job);	
			}catch(Exception e){
				logger.error("server run exception");
				try {
					socket.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) {
		Server server;
		try{
			 server = new Server();
			 server.service();
		}catch(Exception e){
			e.printStackTrace();
			logger.error("server socket establish error!");
		}
	}
}
服務器業務執行線程:

package com.test.server.business;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.test.server.config.Configuration;
import com.test.tools.SocketIO;

public class Job implements Runnable {
	static Logger logger = Logger.getLogger(Job.class);
	private Socket socket;
	
	public Job(Socket socket){
		this.socket = socket;
	}

	public void run() {
		Properties p = Configuration.getConfig();
		String encoding = p.getProperty("socketStreamEncoding");
		
		DataInputStream input = null;
		DataOutputStream output = null;
		try{
			input = SocketIO.getDataInput(socket);
		
			short length = input.readShort();
			byte[] bytes = new byte[length];
			input.read(bytes);
			String user = new String(bytes,encoding);
			short pwd = input.readShort();
			
			String result = null;
			if(null != user && !user.equals("") && user.equals("name") && pwd == 123){
				result = "login success";
			}else{
				result = "login failed";
			}
			logger.info("request user:"+user);
			logger.info("request pwd:"+pwd);
			
			output = SocketIO.getDataOutput(socket);
			
			bytes = result.getBytes(encoding);
			length = (short)bytes.length;
			output.writeShort(length);
			output.write(bytes);
			
			logger.info("response info:"+result);
		}catch(Exception e){
			e.printStackTrace();
			logger.error("business thread run exception");
		}finally{
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
				logger.error("server socket close error");
			}
		}
	}
}

配置文件類:

package com.test.server.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;

public class Configuration {
	private static Properties config;
	
	static Logger logger = Logger.getLogger(Configuration.class);
	
	public static Properties getConfig(){
		try{
			if(null == config){
				File configFile = new File("./conf/conf.properties");
				if(configFile.exists() && configFile.isFile()
						&& configFile.canRead()){
					InputStream input = new FileInputStream(configFile);
					config = new Properties();
					config.load(input);
				}
			}
		}catch(Exception e){
			//default set
			config = new Properties();
			config.setProperty("protocol", "TLSV1");
			config.setProperty("serverCertificateFile", "./certificate/server_rsa.key");
			config.setProperty("serverCertificatePwd", "123456");
			config.setProperty("serverMainPwd", "654321");
			config.setProperty("clientCertificateFile", "./certificate/client_rsa.key");
			config.setProperty("clientCertificatePwd", "123456");
			config.setProperty("clientMainPwd", "654321");
			config.setProperty("serverListenPort", "10000");
			config.setProperty("serverThreadPoolSize", "5");
			config.setProperty("serverRequestQueueSize", "10");
			config.setProperty("socketStreamEncoding", "UTF-8");
		}
		return config;
	}
}

接口工具類:

package com.test.tools;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;

public class SocketIO{
	public static DataInputStream getDataInput(Socket socket) throws IOException{
		DataInputStream input = new DataInputStream(socket.getInputStream());
		return input;
	}
	
	public static DataOutputStream getDataOutput(Socket socket) throws IOException{
		DataOutputStream out = new DataOutputStream(socket.getOutputStream());
		return out;
	}
}

配置文件:

#1:單向認證,只有服務器端需證明其身份
#2:雙向認證,服務器端和客戶端都需證明其身份
authority=2
#通信協議
protocol=TLSV1
#服務器證書
serverCertificateFile=./certificate/server_rsa.key
#服務器證書密碼
serverCertificatePwd=123456
#服務器證書主密碼
serverMainPwd=654321
#客戶端證書,如果為雙向認證,則必須填寫
clientCertificateFile=./certificate/client_rsa.key
#客戶端證書密碼
clientCertificatePwd=123456
#客戶端證書主密碼
clientMainPwd=654321
#服務器監聽端口,注意root權限
serverListenPort=10000
#服務器線程池線程數(2*核數+1)
serverThreadPoolSize=5
#服務器Socket請求隊列長度
serverRequestQueueSize=10
#字節流編碼
socketStreamEncoding=GBK

日志文件:

log4j.rootLogger=debug,logOutput,fileLogOutput

log console out put 
log4j.appender.logOutput=org.apache.log4j.ConsoleAppender
log4j.appender.logOutput.layout=org.apache.log4j.PatternLayout
log4j.appender.logOutput.layout.ConversionPattern=%p%d{[yy-MM-dd HH:mm:ss]}[%c] -> %m%n

#log file out put
log4j.appender.fileLogOutput=org.apache.log4j.RollingFileAppender
log4j.appender.fileLogOutput.File=./log/server.log
log4j.appender.fileLogOutput.MaxFileSize=1000KB
log4j.appender.fileLogOutput.MaxBackupIndex=3
log4j.appender.fileLogOutput.layout=org.apache.log4j.PatternLayout
log4j.appender.fileLogOutput.layout.ConversionPattern=%p%d{[yy-MM-dd HH:mm:ss]}[%c] -> %m%n

運行后的結果:

客戶端:

INFO[13-10-08 09:33:39][com.test.client.Client] -> request result:login success

服務端:

INFO[13-10-08 09:33:34][com.test.server.Server] -> Server start up!
INFO[13-10-08 09:33:34][com.test.server.Server] -> server port is:10000
DEBUG[13-10-08 09:33:34][com.test.server.Server] -> Wait for client request!
DEBUG[13-10-08 09:33:39][com.test.server.Server] -> Get client request!
DEBUG[13-10-08 09:33:39][com.test.server.Server] -> Wait for client request!
INFO[13-10-08 09:33:39][com.test.server.business.Job] -> request user:name
INFO[13-10-08 09:33:39][com.test.server.business.Job] -> request pwd:123
INFO[13-10-08 09:33:39][com.test.server.business.Job] -> response info:login success

 

PS:

1,不能隨意的使用close()方法關閉socket輸入輸出流,使用close()方法關閉socket輸入輸出流會導致socket本身被關閉

2,字符串必須按照指定的編碼轉換為字節數組,字節數組也必須通過相同的編碼轉換為字符串,否則將會出現亂碼

String[] pwdsuits = socket.getSupportedCipherSuites();
socket.setEnabledCipherSuites(pwdsuits);

加密套件(ciphersuits)包括一組加密參數,這些參數指定了加密算法、密鑰長度等加密等信息。

[SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, ...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM