排序算法Ruby Part1

1、Bubble sort 冒泡排序

  # Bubble sort 冒泡排序
  # 每次扫描,比较和交换相邻元素,保证一次扫描后,最大元素在最后一个
  # 每次扫描后,扫描队列长度减一
  # Time Complexity: О(n^2)
  # Space Complexity: О(n) total, O(1) auxiliary
  # Stable: Yes
  def bubble_sort(container)
    swap=true
    while(swap)
      swap=false
      for i in 0..(container.size-1) do
        for j in 0..i do
          if(container[i]<container[j])
            r=container[j]
            container[j]=container[i]
            container[i]=r
            swap=true
          end
        end
      end
    end

    return container
  end

2、Selection sort 选择排序

  # Selection sort 选择排序
  # 从头扫描到尾,每次将最小元素放到第一个
  # 每次扫描后,队列长度减一
  # Time Complexity: О(n^2)
  # Space Complexity: О(n) total, O(1) auxiliary
  # Stable: Yes
  def selection_sort(container)
    for i in 0..container.size-1 do
      min = i
      for j in i..container.size-1 do
        if(container[min]>container[j])
          min=j
        end
      end

      r=container[i]
      container[i]=container[min]
      container[min]=r

    end

    return container

  end

3、Insertion sort 插入排序

  # Insertion sort 插入排序
  # 起始队列长度为1,每次向队列增加1个数字
  # 通过元素移动,将队列调整为有序状态
  # Time Complexity: О(n^2)
  # Space Complexity: О(n) total, O(1) auxiliary
  # Stable: Yes
  def insertion_sort(container)
    if container.size <2
      return container
    end

    for i in 1..container.size-1 do
      val = container[i]
      j=i-1
      while(j>=0 and container[j]>val) do
        container[j+1]=container[j]
        j=j-1
      end

      container[j+1] = val
    end

    return container
  end

4、Shell Sort 希尔排序

  # Shell Sort 希尔排序
  # 指定一个步长,将需要排序的数字,按序号%步长分组
  # 对每组进行插入排序,然后减小步长,再次分组,排序
  # 直到步长为1结束
  # Time Complexity: О(n^2)
  # Space Complexity: О(n) total, O(1) auxiliary
  # Stable: Yes
  def shell_sort(container)
    step = container.size/2
    while step>0 do
      for i in step..container.size-1 do
        val= container[i]
        j=i-step
        while(j>=0 and container[j]>val) do
          container[j+step] = container[j]
          j=j-step
        end
        container[j+step]=val
      end

      #puts(">>")
      #puts(container)

      step = step/2
    end

    return container
  end

5、Merge sort 归并排序

  # Merge sort 归并排序
  # 二路归并首先将归并长度定为2,在归并集内进行排序
  # 然后归并长度×2,将有序集合进行归并
  # Time Complexity: О(nlogn) average and worst-case
  # Space Complexity: О(n) auxiliary
  # Stable: Yes
  def mergesort(container)
    return container if container.size <= 1

    mid = container.size / 2
    left = container[0...mid]
    right = container[mid...container.size]

    merge(mergesort(left), mergesort(right))
  end

  private

  def merge(left, right)
    sorted = []
    until left.empty? or right.empty?
      left.first <= right.first ? sorted << left.shift : sorted << right.shift
    end
    sorted + left + right
  end

C# Https Soap Client

1、Soap Https Soap Client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

namespace IISSoapClientTest
{
    class Program
    {
        public static void HelloHttp(string url)
        {
            Hello h = new Hello(url);
            string ans = h.HelloWorld("C# http client");
            Console.WriteLine(ans);
            Console.WriteLine();
        }

        //同样的证书,IIS可以过,Tomcat过不去
        public static void HelloHttps(string url,String certPath)
        {
            X509CertificateCollection certs = new X509CertificateCollection();
            X509Certificate cert = X509Certificate.CreateFromCertFile(certPath);

            Hello h = new Hello(url);
            h.ClientCertificates.Add(cert);
            string ans = h.HelloWorld("C# https client");
            Console.WriteLine(ans);
            Console.WriteLine();
        }

        //绕过证书检查
        public static void HelloHttpsWithRemoteCertificateValidationCallback(string url)
        {
            //ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteCertificateValidationCallback);

            Hello h = new Hello(url);
            string ans = h.HelloWorld("C# https client");
            Console.WriteLine(ans);
            Console.WriteLine();
        }

        private static bool RemoteCertificateValidationCallback(object sender, X509Certificate certificate, 
            X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }  

        static void Main(string[] args)
        {
            //HelloHttp("http://127.0.0.1:80/Hello.asmx");
            //HelloHttps("https://127.0.0.1:443/Hello.asmx");
            //HelloHttpsWithRemoteCertificateValidationCallback("https://127.0.0.1:443/Hello.asmx");

            //HelloHttp("http://127.0.0.1:8080/SoapTest/services/HelloService");
            HelloHttps("https://127.0.0.1:8443/SoapTest/services/HelloService", @"D:\DiskE\Projects\VS2010\TestProjects\SSLSocket\myKeyStore.cer");
            //HelloHttpsWithRemoteCertificateValidationCallback("https://127.0.0.1:8443/SoapTest/services/HelloService");
        }
    }
}

Java Https Soap Server(Tomcat-Axis2)

1、%Tomcat%/server/server.xml
找到下面一段:

<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
-->

替换为:

<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" SSLEnabled="true"  
	    maxThreads="150" scheme="https"  secure="true"
	    clientAuth="false" sslProtocol="TLS"
	    disableUploadTimeout="true" enableLookups="false"
	    keystoreFile="D:/JavaContainer/apache-tomcat-6.0.35-x86/myKeyStore.jks"
	    keystorePass="sslTestPwd"
/>

这样,就可以用https://127.0.0.1:8443访问Tomcat了。

2、在需要使用https项目的axis2.xml文件中,增加下面内容

        <!--修改-->
	<transportReceiver name="http"
		class="org.apache.axis2.transport.http.AxisServletListener">
		<parameter name="port">8080</parameter>
	</transportReceiver>
        <!--新增-->
	<transportReceiver name="https"
		class="org.apache.axis2.transport.http.AxisServletListener">
		<parameter name="port">8443</parameter>
	</transportReceiver>

这样,该WebService就可以使用https进行访问了:)

C# Https Soap Server(IIS7)

1、首先准备一个p12格式的服务端证书
无论是购买,还是用openssl或java keytool生成自签名证书都可以

2、在IIS7的根目录,选中“安全性->根目录证书”,选择“导入”即可

3、如果显示证书链有问题,则在IE中导入CA证书就好了

4、在需要HTTPS的网站上,选择“绑定”,绑定类型为https,选择需要的证书

5、在客户端的IE中,导入CA证书就好了

Java Https Soap Client(Axis2)

1、SoapClient

package com.neohope;

import java.net.URL;
import java.rmi.RemoteException;

public class SoapClientTest {
	
	public static void HelloHttp(String url) throws RemoteException
	{
		HelloStub h = new HelloStub(url);
		com.neohope.HelloStub.HelloWorld hello = new com.neohope.HelloStub.HelloWorld();
		hello.setName("Java http client");
		com.neohope.HelloStub.HelloWorldResponse rsp = h.helloWorld(hello);
		System.out.println(rsp.getHelloWorldResult());
	}
	
	public static void HelloHttps(String url,String trustStorePath,String trustStorePwd) throws RemoteException
	{
		URL jksurl = SoapClientTest.class.getClassLoader().getResource(
				"myTrustStore.jks");
		String jks = jksurl.getFile();
		System.setProperty("javax.net.ssl.trustStore", jks);
		System.setProperty("javax.net.ssl.trustStorePassword", trustStorePwd);
		
		HelloStub h = new HelloStub(url);
		com.neohope.HelloStub.HelloWorld hello = new com.neohope.HelloStub.HelloWorld();
		hello.setName("Java https client");
		com.neohope.HelloStub.HelloWorldResponse rsp = h.helloWorld(hello);
		System.out.println(rsp.getHelloWorldResult());
	}
	
	
	public static void main(String[] args) throws RemoteException
	{
		//HelloHttp("http://localhost:80/Hello.asmx");
		HelloHttps("https://localhost:443/Hello.asmx","myTrustStore.jks","sslTestPwd");
	}
}

2、SoapClientWithContextTest

package com.neohope;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.rmi.RemoteException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

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

public class SoapClientWithContextTest {
	
	public static void HelloHttp(String url) throws RemoteException
	{
		HelloStub h = new HelloStub(url);
		com.neohope.HelloStub.HelloWorld hello = new com.neohope.HelloStub.HelloWorld();
		hello.setName("Java http client");
		com.neohope.HelloStub.HelloWorldResponse rsp = h.helloWorld(hello);
		System.out.println(rsp.getHelloWorldResult());
	}
	
	public static void HelloHttps(String url,String trustStorePath,String trustStorePwd) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, CertificateException, FileNotFoundException, IOException
	{
		URL jksurl = SoapClientTest.class.getClassLoader().getResource(
				"myTrustStore.jks");
		String jks = jksurl.getFile();
		
		KeyStore trustStore = KeyStore.getInstance("JKS");
		trustStore.load(new FileInputStream(jks), trustStorePwd.toCharArray());
		TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
		trustManagerFactory.init(trustStore);
        
		SSLContext sslContext = SSLContext.getInstance("TLSv1");
		//SSLContext sslContext = SSLContext.getInstance("SSLv3");
		
		sslContext.init(new KeyManager[0], trustManagerFactory.getTrustManagers(), null);
		SSLContext.setDefault(sslContext);
		
		HelloStub h = new HelloStub(url);
		com.neohope.HelloStub.HelloWorld hello = new com.neohope.HelloStub.HelloWorld();
		hello.setName("Java https client");
		com.neohope.HelloStub.HelloWorldResponse rsp = h.helloWorld(hello);
		System.out.println(rsp.getHelloWorldResult());
	}
	
	
	public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException
	{
		//HelloHttp("http://localhost:80/Hello.asmx");
		HelloHttps("https://localhost:443/Hello.asmx","myTrustStore.jks","sslTestPwd");
	}
}

3、SoapClientWithTrustManagerTest
可以绕过证书检查

package com.neohope;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.rmi.RemoteException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

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

public class SoapClientWithTrustManagerTest {
	
	public static void HelloHttp(String url) throws RemoteException
	{
		HelloStub h = new HelloStub(url);
		com.neohope.HelloStub.HelloWorld hello = new com.neohope.HelloStub.HelloWorld();
		hello.setName("Java http client");
		com.neohope.HelloStub.HelloWorldResponse rsp = h.helloWorld(hello);
		System.out.println(rsp.getHelloWorldResult());
	}
	
	public static void HelloHttps(String url,String trustStorePath,String trustStorePwd) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, CertificateException, FileNotFoundException, IOException
	{        
		SSLContext sslContext = SSLContext.getInstance("TLSv1");
		//SSLContext sslContext = SSLContext.getInstance("SSLv3");
		
		sslContext.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
		SSLContext.setDefault(sslContext);
		
		HelloStub h = new HelloStub(url);
		com.neohope.HelloStub.HelloWorld hello = new com.neohope.HelloStub.HelloWorld();
		hello.setName("Java https client");
		com.neohope.HelloStub.HelloWorldResponse rsp = h.helloWorld(hello);
		System.out.println(rsp.getHelloWorldResult());
	}
	
	private static class DefaultTrustManager implements X509TrustManager {

		@Override
		public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
		}

		@Override
		public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	}
	
	
	public static void main(String[] args) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException
	{
		//HelloHttp("http://localhost:80/Hello.asmx");
		HelloHttps("https://localhost:443/Hello.asmx","myTrustStore.jks","sslTestPwd");
	}
}

SSLSocket Java Part4

1、证书生成
generateKey.bat

Set Path=%JAVA_HOME%\bin;%PATH%
#生成私钥
keytool -validity 10000 -genkey -alias sslTestKey -keystore myKeyStore.jks -keypass sslTestPwd -storepass sslTestPwd -dname "CN=AtlasTiger, OU=AtlasTiger, O=AtlasTiger, L=ShangHai, ST=ShangHai, C=CN"

pause

2、导出公钥证书Cert
exportCert.bat

Set Path=%JAVA_HOME%\bin;%PATH%
#导出证书
keytool -export -keystore myKeyStore.jks -storepass sslTestPwd -keypass sslTestPwd -alias sslTestKey -file myKeyStore.crt

pause

3、导出TurstStore
exportTrustSotre.bat

Set Path=%JAVA_HOME%\bin;%PATH%
#导入证书生成TurstStore
keytool -import -file myKeyStore.crt -alias sslTestKey -keystore myTrustStore.jks -keypass sslTestPwd -storepass sslTestPwd

pause

4、导出私钥P12格式
exportP12.bat

Set Path=%JAVA_HOME%\bin;%PATH%

keytool -importkeystore -srckeystore myKeyStore.jks -destkeystore myKeyStore.p12 -deststoretype PKCS12 -srcstorepass password -deststorepass password

pause

SSLSocket C# Part1

1、SSLSocket Server

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;

namespace SSLSocket
{
    class SSLSocketServer
    {
        static X509Certificate serverCertificate = null;
        static String delimiter = "=========================================================";

        public static void RunServer(String ip,int port,String p12Path)
        {
            serverCertificate = new X509Certificate2(p12Path, "sslTestPwd");

            TcpListener listener = new TcpListener(IPAddress.Parse(ip), port);
            listener.Start();
            while (true)
            {
                try
                {
                    TcpClient client = listener.AcceptTcpClient();
                    ProcessClient(client);
                }
                catch(Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }

        static void ProcessClient(TcpClient client)
        {
            SslStream sslStream = new SslStream(client.GetStream(), false);
            try
            {
                //sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls | SslProtocols.Ssl2 | SslProtocols.Ssl3 | SslProtocols.None, true);
                sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Ssl2 | SslProtocols.Ssl3, true);
                DisplaySecurityLevel(sslStream);
                DisplayCertificateInformation(sslStream);

                sslStream.ReadTimeout = 5000;
                sslStream.WriteTimeout = 5000;
                string messageData = ReadMessage(sslStream);
                Console.WriteLine(delimiter);
                Console.WriteLine("收到信息: {0}", messageData);
                Console.WriteLine(delimiter);
                //byte[] message = Encoding.UTF8.GetBytes("Hello from the server.");
                //Console.WriteLine("Sending hello message.");
                //sslStream.Write(message);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Exception: {0}", e.Message);
                if (e.InnerException != null)
                {
                    Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
                }
                Console.WriteLine("Authentication failed - closing the connection.");
                sslStream.Close();
                client.Close();
                return;
            }
            finally
            {
                sslStream.Close();
                client.Close();
            }
        }

        static string ReadMessage(SslStream sslStream)
        {
            byte[] buffer = new byte[2048];
            StringBuilder messageData = new StringBuilder();
            int bytes = -1;
            do
            {
                bytes = sslStream.Read(buffer, 0, buffer.Length);
                Decoder decoder = Encoding.UTF8.GetDecoder();
                char[] chars = new char[decoder.GetCharCount(buffer, 0, bytes)];
                decoder.GetChars(buffer, 0, bytes, chars, 0);
                messageData.Append(chars);
                if (messageData.ToString().IndexOf("") != -1)
                {
                    break;
                }
            }
            while (bytes != 0);

            return messageData.ToString();
        }

        static void DisplaySecurityLevel(SslStream stream)
        {
            Console.WriteLine(delimiter);
            Console.WriteLine("通讯协议: {0}", stream.SslProtocol);
            Console.WriteLine("加密算法: {0} strength {1}", stream.CipherAlgorithm, stream.CipherStrength);
            Console.WriteLine("哈希算法: {0} strength {1}", stream.HashAlgorithm, stream.HashStrength);
            Console.WriteLine("密钥交换算法: {0} strength {1}", stream.KeyExchangeAlgorithm, stream.KeyExchangeStrength);
            Console.WriteLine(delimiter);
        }

        static void DisplayCertificateInformation(SslStream stream)
        {
            Console.WriteLine(delimiter);
            Console.WriteLine("证书吊销列表检查: {0}", stream.CheckCertRevocationStatus);

            X509Certificate localCertificate = stream.LocalCertificate;
            if (stream.LocalCertificate != null)
            {
                Console.WriteLine("本地证书签发者: {0}", localCertificate.Subject);
                Console.WriteLine("本地证书有效期: {0}~{1}", localCertificate.GetEffectiveDateString(),
                    localCertificate.GetExpirationDateString());
            }
            else
            {
                Console.WriteLine("本地证书为空");
            }

            X509Certificate remoteCertificate = stream.RemoteCertificate;
            if (stream.RemoteCertificate != null)
            {
                Console.WriteLine("远程证书签发者: {0}", remoteCertificate.Subject);
                Console.WriteLine("远程证书有效期: {0}至{1}", remoteCertificate.GetEffectiveDateString(),
                    remoteCertificate.GetExpirationDateString());
            }
            else
            {
                Console.WriteLine("远程证书为空");
            }
            Console.WriteLine(delimiter);
        }

    }
}

2、SSLSocket Client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;

namespace SSLSocketClient
{
    class SSLSocketClient
    {
        //回调函数验证证书
        public static bool ValidateServerCertificate(
              object sender,
              X509Certificate certificate,
              X509Chain chain,
              SslPolicyErrors sslPolicyErrors)
        {
            if (sslPolicyErrors == SslPolicyErrors.None)
            {
                return true;
            }

            if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNameMismatch || sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors)
            {
                return true;
            }

            return false;
        }

        public static void SendMessage(string ip, int port,String certPath, String msg)
        {
            TcpClient client = new TcpClient(ip, port);
            SslStream sslStream = new SslStream(client.GetStream(),
                false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);

            X509CertificateCollection certs = new X509CertificateCollection();
            X509Certificate cert = X509Certificate.CreateFromCertFile(certPath);
            certs.Add(cert);

            try
            {
                sslStream.AuthenticateAsClient("AtlasTiger", certs, SslProtocols.Tls, false);
                //sslStream.AuthenticateAsClient("AtlasTiger", certs, SslProtocols.Ssl3, false);

                //sslStream.AuthenticateAsClient("AtlasTiger", certs, SslProtocols.Ssl2, false);
                //sslStream.AuthenticateAsClient("AtlasTiger", certs, SslProtocols.None, false);
            }
            catch (AuthenticationException e)
            {
                Console.WriteLine("Authentication failed : " + e);
                client.Close();
                return;
            }

            byte[] messsage = Encoding.UTF8.GetBytes(msg);
            sslStream.Write(messsage);
            sslStream.Flush();

            client.Close();
        }
    }
}

SSLSocket Java Part3

1、SSLSocket Client绕过证书检查

package com.ats.ssl.socket;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class ClientWithTrustManager {
	
	public static void connectAndSend(String trustStorePath,
			String trustStorePwd, String ip, int port, String msg) throws IOException, NoSuchAlgorithmException, KeyManagementException{
        
		SSLContext sslContext = SSLContext.getInstance("TLS");
		//SSLContext sslContext = SSLContext.getInstance("SSLv3");
		sslContext.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
		SSLContext.setDefault(sslContext);
		
		SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();  
		SSLSocket sslsocket = (SSLSocket) sslSocketFactory.createSocket(
				"localhost", 9999);

		try {
			OutputStream outputstream = sslsocket.getOutputStream();
			OutputStreamWriter outputstreamwriter = new OutputStreamWriter(
					outputstream);
			BufferedWriter bufferedwriter = new BufferedWriter(
					outputstreamwriter);

			bufferedwriter.write(msg);
			bufferedwriter.flush();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			sslsocket.close();
		}
	}

	private static class DefaultTrustManager implements X509TrustManager {

		@Override
		public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
		}

		@Override
		public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
		}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	}
	
	public static void main(String[] args) throws Exception {
		try {
			URL url = Server.class.getClassLoader().getResource(
					"myTrustStore.jks");
			String jks = url.getFile();

			connectAndSend(jks, "sslTestPwd", "127.0.0.1", 9999,
					"This msg is from Java SSL Client :)");

		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}
}

SSLSocket Java Part2

1、SSLSocket Java Server使用SSLContext

package com.ats.ssl.socket;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class ServerWithContext {

	static String delimiter = "=========================================================";

	public static void startListen(String keyStorePath, String keyStorePwd, int port) throws IOException, KeyStoreException, NoSuchAlgorithmException,
			CertificateException, UnrecoverableKeyException, KeyManagementException {

		KeyStore keyStore = KeyStore.getInstance("JKS");
		keyStore.load(new FileInputStream(keyStorePath), keyStorePwd.toCharArray());
		KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
		keyManagerFactory.init(keyStore, keyStorePwd.toCharArray());

		//SSLContext sslContext = SSLContext.getInstance("TLSv1");
		SSLContext sslContext = SSLContext.getInstance("SSLv3");
		sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[0], null);

		SSLServerSocketFactory sslserversocketfactory = sslContext.getServerSocketFactory();
		SSLServerSocket sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(port);

		while (true) {
			SSLSocket sslsocket = (SSLSocket) sslserversocket.accept();

			DisplaySecurityLevel(sslsocket);
			DisplayCertificateInformation(sslsocket);

			try {
				InputStream inputstream = sslsocket.getInputStream();
				InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
				BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

				System.out.println(delimiter);
				String string = null;
				while ((string = bufferedreader.readLine()) != null) {
					System.out.println(string);
					System.out.flush();
				}
				System.out.println(delimiter);
			} catch (Exception ex) {
				ex.printStackTrace();
			} finally {
				sslsocket.close();
			}
		}
	}

	static void DisplaySecurityLevel(SSLSocket sslsocket) {
		System.out.println(delimiter);
		SSLSession session = sslsocket.getSession();
		System.out.println("通讯协议: " + session.getProtocol());
		System.out.println("加密方式: " + session.getCipherSuite());
		System.out.println(delimiter);
	}

	static void DisplayCertificateInformation(SSLSocket sslsocket) {
		System.out.println(delimiter);
		Certificate[] localCertificates = sslsocket.getSession().getLocalCertificates();
		if (localCertificates == null || localCertificates.length == 0) {
			System.out.println("本地证书为空");
		} else {
			Certificate cert = localCertificates[0];
			System.out.println("本地证书类型: " + cert.getType());
			if (cert.getType().equals("X.509")) {
				X509Certificate x509 = (X509Certificate) cert;
				System.out.println("本地证书签发者: " + x509.getIssuerDN());
				System.out.println("本地证书有效期: " + x509.getNotBefore() + "至" + x509.getNotAfter());
			}
		}

		try {
			Certificate[] peerCertificates = sslsocket.getSession().getPeerCertificates();

			if (peerCertificates == null || peerCertificates.length == 0) {
				System.out.println("远程证书为空");
			} else {
				Certificate cert = peerCertificates[0];
				System.out.println("远程证书类型: " + cert.getType());
				if (cert.getType().equals("X.509")) {
					X509Certificate x509 = (X509Certificate) cert;
					System.out.println("远程证书签发者: " + x509.getIssuerDN());
					System.out.println("远程证书有效期: " + x509.getNotBefore() + "至" + x509.getNotAfter());
				}
			}
		} catch (SSLPeerUnverifiedException e) {
			// e.printStackTrace();
			System.out.println("远程证书为空");
		}

		System.out.println(delimiter);
	}

	public static void main(String[] arstring) {
		try {
			URL url = ServerWithContext.class.getClassLoader().getResource("myKeyStore.jks");
			String jks = url.getFile();
			startListen(jks, "sslTestPwd", 9999);

		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}
}

2、SSLSocket Java Client使用SSLContext

package com.ats.ssl.socket;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

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

public class ClientWithContext {
	
	public static void connectAndSend(String trustStorePath,
			String trustStorePwd, String ip, int port, String msg) throws IOException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, CertificateException, UnrecoverableKeyException{
	
		KeyStore trustStore = KeyStore.getInstance("JKS");
		trustStore.load(new FileInputStream(trustStorePath), trustStorePwd.toCharArray());
		TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
		trustManagerFactory.init(trustStore);
        
		SSLContext sslContext = SSLContext.getInstance("TLSv1");
		//SSLContext sslContext = SSLContext.getInstance("SSLv3");
		
		sslContext.init(new KeyManager[0], trustManagerFactory.getTrustManagers(), null);
		SSLContext.setDefault(sslContext);
		
		SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();  
		SSLSocket sslsocket = (SSLSocket) sslSocketFactory.createSocket(
				"localhost", 9999);

		try {
			OutputStream outputstream = sslsocket.getOutputStream();
			OutputStreamWriter outputstreamwriter = new OutputStreamWriter(
					outputstream);
			BufferedWriter bufferedwriter = new BufferedWriter(
					outputstreamwriter);

			bufferedwriter.write(msg);
			bufferedwriter.flush();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			sslsocket.close();
		}
	}

	public static void main(String[] args) throws Exception {
		try {
			URL url = Server.class.getClassLoader().getResource(
					"myTrustStore.jks");
			String jks = url.getFile();

			connectAndSend(jks, "sslTestPwd", "127.0.0.1", 9999,
					"This msg is from Java SSL Client :)");

		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}
}

SSLSocket Java Part1

1、使用环境变量,最基本的SSLSocket Server

package com.ats.ssl.socket;

import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

public class Server {

	static String delimiter = "=========================================================";

	public static void startListen(String keyStorePath, String keyStorePwd, int port) throws IOException {
		System.setProperty("javax.net.ssl.keyStore", keyStorePath);
		System.setProperty("javax.net.ssl.keyStorePassword", keyStorePwd);

		SSLServerSocketFactory sslserversocketfactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
		SSLServerSocket sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(port);

		while (true) {
			SSLSocket sslsocket = (SSLSocket) sslserversocket.accept();

			String protocols[] = { "TLSv1" };
			// String protocols[] = {"SSLv2Hello","TLSv1","SSLv3"};
			// String protocols[] = {"SSLv3"};
			sslsocket.setEnabledProtocols(protocols);

			DisplaySecurityLevel(sslsocket);
			DisplayCertificateInformation(sslsocket);

			try {
				InputStream inputstream = sslsocket.getInputStream();
				InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
				BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

				System.out.println(delimiter);
				String string = null;
				while ((string = bufferedreader.readLine()) != null) {
					System.out.println(string);
					System.out.flush();
				}
				System.out.println(delimiter);
			} catch (Exception ex) {
				ex.printStackTrace();
			} finally {
				sslsocket.close();
			}
		}
	}

	static void DisplaySecurityLevel(SSLSocket sslsocket) {
		System.out.println(delimiter);
		SSLSession session = sslsocket.getSession();
		System.out.println("通讯协议: " + session.getProtocol());
		System.out.println("加密方式: "+session.getCipherSuite());
		System.out.println(delimiter);
	}

	static void DisplayCertificateInformation(SSLSocket sslsocket) {
		System.out.println(delimiter);
		Certificate[] localCertificates = sslsocket.getSession().getLocalCertificates();
		if (localCertificates == null || localCertificates.length == 0) {
			System.out.println("本地证书为空");
		} else {
			Certificate cert = localCertificates[0];
			System.out.println("本地证书类型: " + cert.getType());
			if (cert.getType().equals("X.509")) {
				X509Certificate x509 = (X509Certificate) cert;
				System.out.println("本地证书签发者: " + x509.getIssuerDN());
				System.out.println("本地证书有效期: " + x509.getNotBefore() + "至" + x509.getNotAfter());
			}
		}

		try {
			Certificate[] peerCertificates = sslsocket.getSession().getPeerCertificates();

			if (peerCertificates == null || peerCertificates.length == 0) {
				System.out.println("远程证书为空");
			} else {
				Certificate cert = peerCertificates[0];
				System.out.println("远程证书类型: " + cert.getType());
				if (cert.getType().equals("X.509")) {
					X509Certificate x509 = (X509Certificate) cert;
					System.out.println("远程证书签发者: " + x509.getIssuerDN());
					System.out.println("远程证书有效期: " + x509.getNotBefore() + "至" + x509.getNotAfter());
				}
			}
		} catch (SSLPeerUnverifiedException e) {
			// e.printStackTrace();
			System.out.println("远程证书为空");
		}

		System.out.println(delimiter);
	}

	public static void main(String[] arstring) {
		try {
			URL url = Server.class.getClassLoader().getResource("myKeyStore.jks");
			String jks = url.getFile();
			startListen(jks, "sslTestPwd", 9999);

		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}
}

2、相应的,使用环境变量进行设置的,SSLSocket Client

package com.ats.ssl.socket;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;
import java.net.URL;

public class Client {
	public static void connectAndSend(String trustStorePath,
			String trustStorePwd, String ip, int port, String msg)
			throws IOException {
		System.setProperty("javax.net.ssl.trustStore", trustStorePath);
		System.setProperty("javax.net.ssl.trustStorePassword", trustStorePwd);

		SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory
				.getDefault();
		SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(
				"localhost", 9999);

		//String protocols[] = {"TLSv1"};
		String protocols[] = {"SSLv2Hello","TLSv1","SSLv3"};
		//String protocols[] = {"SSLv3"};
		sslsocket.setEnabledProtocols(protocols);

		try {
			OutputStream outputstream = sslsocket.getOutputStream();
			OutputStreamWriter outputstreamwriter = new OutputStreamWriter(
					outputstream);
			BufferedWriter bufferedwriter = new BufferedWriter(
					outputstreamwriter);

			bufferedwriter.write(msg);
			bufferedwriter.flush();
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			sslsocket.close();
		}
	}

	public static void main(String[] arstring) {
		try {
			URL url = Server.class.getClassLoader().getResource(
					"myTrustStore.jks");
			String jks = url.getFile();

			connectAndSend(jks, "sslTestPwd", "127.0.0.1", 9999,
					"This msg is from Java SSL Client :)");

		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}
}