Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About

15.2. SSL Socket

15.2.1. Java Socket HTTPS

		
package netkiller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class HTTPS {

	public static void main(String[] args) {
	    // Create a trust manager that does not validate certificate chains
	    TrustManager[] trustAllCerts = new TrustManager[]{
	        new X509TrustManager() {
	            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
	                return null;
	            }
	            public void checkClientTrusted(
	                java.security.cert.X509Certificate[] certs, String authType) {
	            }
	            public void checkServerTrusted(
	                java.security.cert.X509Certificate[] certs, String authType) {
	            }
	        }
	    };

	    // Install the all-trusting trust manager
	    try {
	        SSLContext sc = SSLContext.getInstance("SSL");
	        sc.init(null, trustAllCerts, new java.security.SecureRandom());
	        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
	    } catch (Exception e) {
	    }

	    // Now you can access an https URL without having the certificate in the truststore
	    try {
	    	//Create a URL for the desired page
	        URL url = new URL("https://java.sun.com/");

	        // Read all the text returned by the server
	        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
	        String html;
	        while ((html = in.readLine()) != null) {
	            // str is one line of text; readLine() strips the newline character(s)
	        	System.out.println(html);
	        }
	        in.close();

	    } catch (MalformedURLException mue) {
	    } catch (IOException ioe) {
	    }

	}

}

		
		

15.2.2. Java SSL Socket Client

		
package netkiller;

import java.io.*;
import java.net.*;
import javax.net.SocketFactory;
import javax.net.ssl.*;

public class SSLClientSocket {

	public static void main(String[] args) {
	    try {
	        int port = 443;
	        String hostname = "java.sun.com";

	        SocketFactory socketFactory = SSLSocketFactory.getDefault();
	        Socket socket = socketFactory.createSocket(hostname, port);

	        // Create streams to securely send and receive data to the server
	        InputStream in = socket.getInputStream();
	        OutputStream out = socket.getOutputStream();

	        BufferedReader socketReader = new BufferedReader(new InputStreamReader(in));
	        PrintWriter socketWriter = new PrintWriter(out);

	        socketWriter.println("GET /");
	        socketWriter.flush();
	        String line=null;
	        StringBuffer html = new StringBuffer();
	        while((line=socketReader.readLine())!=null){
	        	html.append(line+"\n");
	        }
	        // Read from in and write to out...
	        System.out.println(html.toString());

	        // Close the socket
	        socketReader.close();
	        socketWriter.close();
	        in.close();
	        out.close();
	    } catch(IOException e) {
	    }

	}

}

		
		

15.2.3. Java SSL Socket Server

這裡實現一個簡單的SSL Echo伺服器

創建證書


keytool -genkey -keyalg RSA -alias mycert -keystore mySrvKeystore

		
C:\workspace\test>keytool -genkey -keyalg RSA -alias mycert -keystore mySrvKeystore
輸入keystore密碼:  13721218
您的名字與姓氏是什麼?
  [Unknown]:  陳景峰
您的組織單位名稱是什麼?
  [Unknown]:  中國無線電運動協會
您的組織名稱是什麼?
  [Unknown]:  無線電運動協會
您所在的城市或區域名稱是什麼?
  [Unknown]:  深圳
您所在的州或省份名稱是什麼?
  [Unknown]:  廣東省
該單位的兩字母國家代碼是什麼
  [Unknown]:  CN
CN=陳景峰, OU=中國無線電運動協會, O=無線電運動協會, L=深圳, ST=廣東省, C=CN 正確
嗎?
  [否]:  Y

輸入<mycert>的主密碼
        (如果和 keystore 密碼相同,按回車):  13721218

		
		
C:\workspace\neo>javac netkiller\SSLServerSocket.java



java -Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=13721218 netkiller.SSLServerSocket

Client

C:\workspace\neo>javac netkiller\SSLClientSocket.java java -Djavax.net.ssl.trustStore=truststore -Djavax.net.ssl.trustStorePassword=13721218 netkiller.SSLClientSocket