java SSLContext

1. 什么是SSLSocket

JDK文档指出,SSLSocket扩展Socket并提供使用SSL或TLS协议的安全套接字。

这种套接字是正常的流套接字,但是它们在基础网络传输协议(如TCP)上添加了安全保护层。

具体安全方面的讨论见下一篇。本篇重点关注SSLSocket及相关几个类的使用。

2. SSLSocket和相关类

SSLSocket来自jsse(Java Secure Socket Extension)。

(1)SSLContext: 此类的实例表示安全套接字协议的实现, 它是SSLSocketFactory、SSLServerSocketFactory和SSLEngine的工厂。

(2)SSLSocket: 扩展自Socket

(3)SSLServerSocket: 扩展自ServerSocket

(4)SSLSocketFactory: 抽象类,扩展自SocketFactory, SSLSocket的工厂

(5)SSLServerSocketFactory: 抽象类,扩展自ServerSocketFactory, SSLServerSocket的工厂

(6)KeyStore: 表示密钥和证书的存储设施

(7)KeyManager: 接口,JSSE密钥管理器

(8)TrustManager: 接口,信任管理器(?翻译得很拗口)

(9)X590TrustedManager: TrustManager的子接口,管理X509证书,验证远程安全套接字

3. SSLContext的使用

Java代码  收藏代码
  1. public static void main(String[] args) throws Exception {  
  2.     X509TrustManager x509m = new X509TrustManager() {  
  3.   
  4.         @Override  
  5.         public X509Certificate[] getAcceptedIssuers() {  
  6.             return null;  
  7.         }  
  8.   
  9.         @Override  
  10.         public void checkServerTrusted(X509Certificate[] chain,  
  11.                 String authType) throws CertificateException {  
  12.         }  
  13.   
  14.         @Override  
  15.         public void checkClientTrusted(X509Certificate[] chain,  
  16.                 String authType) throws CertificateException {  
  17.         }  
  18.     };  
  19.     // 获取一个SSLContext实例  
  20.     SSLContext s = SSLContext.getInstance("SSL");  
  21.     // 初始化SSLContext实例  
  22.     s.init(null, new TrustManager[] { x509m },  
  23.             new java.security.SecureRandom());  
  24.     // 打印这个SSLContext实例使用的协议  
  25.     System.out.println("缺省安全套接字使用的协议: " + s.getProtocol());  
  26.     // 获取SSLContext实例相关的SSLEngine  
  27.     SSLEngine e = s.createSSLEngine();  
  28.     System.out  
  29.             .println("支持的协议: " + Arrays.asList(e.getSupportedProtocols()));  
  30.     System.out.println("启用的协议: " + Arrays.asList(e.getEnabledProtocols()));  
  31.     System.out.println("支持的加密套件: "  
  32.             + Arrays.asList(e.getSupportedCipherSuites()));  
  33.     System.out.println("启用的加密套件: "  
  34.             + Arrays.asList(e.getEnabledCipherSuites()));  
  35. }  

 运行结果如下:

SSLContext.getProtocol(): 返回当前SSLContext对象的协议名称

SSLContext.init():  初始化当前SSLContext对象。 三个参数均可以为null。 详见JDK文档。

SSLEngine.getSupportedProtocols()等几个方法可以返回些 Engine上支持/已启用的协议、支持/已启用的加密套件

4. SSLSocket和SSLServerSocket的使用

这两个类的用法跟Socket/ServerSocket的用法比较类似。看下面的例子(主要为了验证SSLSocket的用法 ,I/O和多线程处理比较随意)

4.1 SSLServerSocket

(1)新建一个SSLServerSocket,并开始监听来自客户端的连接

Java代码  收藏代码
  1. // 抛出异常  
  2. // javax.net.ssl.SSLException: No available certificate or key corresponds  
  3. // to the SSL cipher suites which are enabled.  
  4. public static void notOk() throws IOException {  
  5.     SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory  
  6.             .getDefault();  
  7.     SSLServerSocket server = (SSLServerSocket) factory  
  8.             .createServerSocket(10000);  
  9.     System.out.println("ok");  
  10.     server.accept();  
  11. }  

 server.accept()处抛出异常, 提示缺少证书。与ServerSocket不同, SSLServerSocket需要证书来进行安全验证。

使用keytool工具生成一个证书。 步骤如下, 得到一个名为cmkey的证书文件

(2)重新完善上面的代码。 主要增加两个功能: 使用名为cmkey的证书初始化SSLContext, echo客户端的消息。 代码如下

Java代码  收藏代码
  1. // 启动一个ssl server socket  
  2. // 配置了证书, 所以不会抛出异常  
  3. public static void sslSocketServer() throws Exception {  
  4.   
  5.     // key store相关信息  
  6.     String keyName = "cmkey";  
  7.     char[] keyStorePwd = "123456".toCharArray();  
  8.     char[] keyPwd = "123456".toCharArray();  
  9.     KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());  
  10.   
  11.     // 装载当前目录下的key store. 可用jdk中的keytool工具生成keystore  
  12.     InputStream in = null;  
  13.     keyStore.load(in = Test2.class.getClassLoader().getResourceAsStream(  
  14.             keyName), keyPwd);  
  15.     in.close();  
  16.   
  17.     // 初始化key manager factory  
  18.     KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory  
  19.             .getDefaultAlgorithm());  
  20.     kmf.init(keyStore, keyPwd);  
  21.   
  22.     // 初始化ssl context  
  23.     SSLContext context = SSLContext.getInstance("SSL");  
  24.     context.init(kmf.getKeyManagers(),  
  25.             new TrustManager[] { new MyX509TrustManager() },  
  26.             new SecureRandom());  
  27.   
  28.     // 监听和接收客户端连接  
  29.     SSLServerSocketFactory factory = context.getServerSocketFactory();  
  30.     SSLServerSocket server = (SSLServerSocket) factory  
  31.             .createServerSocket(10002);  
  32.     System.out.println("ok");  
  33.     Socket client = server.accept();  
  34.     System.out.println(client.getRemoteSocketAddress());  
  35.   
  36.     // 向客户端发送接收到的字节序列  
  37.     OutputStream output = client.getOutputStream();  
  38.   
  39.     // 当一个普通 socket 连接上来, 这里会抛出异常  
  40.     // Exception in thread "main" javax.net.ssl.SSLException: Unrecognized  
  41.     // SSL message, plaintext connection?  
  42.     InputStream input = client.getInputStream();  
  43.     byte[] buf = new byte[1024];  
  44.     int len = input.read(buf);  
  45.     System.out.println("received: " + new String(buf, 0, len));  
  46.     output.write(buf, 0, len);  
  47.     output.flush();  
  48.     output.close();  
  49.     input.close();  
  50.   
  51.     // 关闭socket连接  
  52.     client.close();  
  53.     server.close();  
  54. }  

4.2 SSLSocket

(1)我们先使用一个普通的Socket尝试连接服务器端

Java代码  收藏代码
  1. // 通过socket连接服务器  
  2. public static void socket() throws UnknownHostException, IOException {  
  3.     Socket s = new Socket("localhost", 10002);  
  4.     System.out.println(s);  
  5.     System.out.println("ok");  
  6.   
  7.     OutputStream output = s.getOutputStream();  
  8.     InputStream input = s.getInputStream();  
  9.   
  10.     output.write("alert".getBytes());  
  11.     System.out.println("sent: alert");  
  12.     output.flush();  
  13.   
  14.     byte[] buf = new byte[1024];  
  15.     int len = input.read(buf);  
  16.     System.out.println("received:" + new String(buf, 0, len));  
  17. }  

 结果客户端和服务器端都出错。 客户端的错误是接收到乱码。 


服务器则抛出异常

javax.NET.ssl.SSLException: Unrecognized SSL message, plaintext connection?

(2)改成SSLSocket, 但是不使用证书。客户端抛出sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Java代码  收藏代码
  1. // 不使用证书, 通过ssl socket连接服务器  
  2. // 抛出异常, 提示找不到证书  
  3. public static void sslSocket() throws UnknownHostException, IOException {  
  4.     SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory  
  5.             .getDefault();  
  6.     SSLSocket s = (SSLSocket) factory.createSocket("localhost", 10002);  
  7.     System.out.println("ok");  
  8.   
  9.     OutputStream output = s.getOutputStream();  
  10.     InputStream input = s.getInputStream();  
  11.   
  12.     output.write("alert".getBytes());  
  13.     System.out.println("sent: alert");  
  14.     output.flush();  
  15.   
  16.     byte[] buf = new byte[1024];  
  17.     int len = input.read(buf);  
  18.     System.out.println("received:" + new String(buf, 0, len));  
  19. }  

程序客户在不持有证书的情况下直接进行连接,服务器端会产生运行时异常javax.Net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown,不允许进行连接。 我们可以指定像下面这样执行客户端,服务器端可以成功echo客户端的发出的字符串"alert"

 Java  -Djavax.net.ssl.trustStore=cmkey Client

这里的cmkey即前面生成的证书文件。

(3)改成SSLSocket, 对SSLContext进行如下初始化。

Java代码  收藏代码
  1. public static void sslSocket2() throws Exception {  
  2.     SSLContext context = SSLContext.getInstance("SSL");  
  3.                // 初始化  
  4.     context.init(null,  
  5.             new TrustManager[] { new Test2.MyX509TrustManager() },  
  6.             new SecureRandom());  
  7.     SSLSocketFactory factory = context.getSocketFactory();  
  8.     SSLSocket s = (SSLSocket) factory.createSocket("localhost", 10002);  
  9.     System.out.println("ok");  
  10.   
  11.     OutputStream output = s.getOutputStream();  
  12.     InputStream input = s.getInputStream();  
  13.   
  14.     output.write("alert".getBytes());  
  15.     System.out.println("sent: alert");  
  16.     output.flush();  
  17.   
  18.     byte[] buf = new byte[1024];  
  19.     int len = input.read(buf);  
  20.     System.out.println("received:" + new String(buf, 0, len));  
  21. }  

 服务器端可以成功echo客户端的发出的字符串"alert"。 完整代码见附件。

参考  http://java.ccidnet.com/art/3737/20060808/789375_1.html

 http://blog.csdn.net/scliu0718/article/details/7198889

http://www.iteye.com/topic/1114800

http://410063005.iteye.com/blog/1751243

原文地址:https://www.cnblogs.com/duanqiao123/p/6881743.html