>>分享Java编程技术,对《Java面向对象编程》等书籍提供技术支持 书籍支持  卫琴直播  品书摘要  在线测试  资源下载  联系我们
发表一个新主题 开启一个新投票 回复文章 您是本文章第 29238 个阅读者 刷新本主题
 * 贴子主题:  SSLSocket的使用 回复文章 点赞(0)  收藏  
作者:日月光华    发表时间:2019-12-31 21:03:14     消息  查看  搜索  好友  邮件  复制  引用

SSLSocket的使用

1. 什么是SSLSocket

JDK文档指出,SSLSocket扩展Socket并提供使用SSL或TLS协议的安全套接字。
这种套接字是正常的流套接字,但是它们在基础网络传输协议(如TCP)上添加了安全保护层。
具体安全方面的讨论见下一篇。本篇重点关注SSLSocket及相关几个类的使用。

2. SSLSocket和相关类

SSLSocket来自jsse(Java Secure Socket Extension)。

点击在新窗口中浏览原图
CTRL+鼠标滚轮放大或缩小

(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代码  
public static void main(String[] args) throws Exception {  
    X509TrustManager x509m = new X509TrustManager() {  
  
        @Override  
        public X509Certificate[] getAcceptedIssuers() {  
            return null;  
        }  
  
        @Override  
        public void checkServerTrusted(X509Certificate[] chain,  
                String authType) throws CertificateException {  
        }  
  
        @Override  
        public void checkClientTrusted(X509Certificate[] chain,  
                String authType) throws CertificateException {  
        }  
    };  
    // 获取一个SSLContext实例  
    SSLContext s = SSLContext.getInstance("SSL");  
    // 初始化SSLContext实例  
    s.init(null, new TrustManager[] { x509m },  
            new java.security.SecureRandom());  
    // 打印这个SSLContext实例使用的协议  
    System.out.println("缺省安全套接字使用的协议: " + s.getProtocol());  
    // 获取SSLContext实例相关的SSLEngine  
    SSLEngine e = s.createSSLEngine();  
    System.out  
            .println("支持的协议: " + Arrays.asList(e.getSupportedProtocols()));  
    System.out.println("启用的协议: " + Arrays.asList(e.getEnabledProtocols()));  
    System.out.println("支持的加密套件: "  
            + Arrays.asList(e.getSupportedCipherSuites()));  
    System.out.println("启用的加密套件: "  
            + Arrays.asList(e.getEnabledCipherSuites()));  
}  

public static void main(String[] args) throws Exception {

X509TrustManager x509m = new X509TrustManager() {



@Override

public X509Certificate[] getAcceptedIssuers() {

return null;

}



@Override

public void checkServerTrusted(X509Certificate[] chain,

String authType) throws CertificateException {

}



@Override

public void checkClientTrusted(X509Certificate[] chain,

String authType) throws CertificateException {

}

};

// 获取一个SSLContext实例

SSLContext s = SSLContext.getInstance("SSL");

// 初始化SSLContext实例

s.init(null, new TrustManager[] { x509m },

new java.security.SecureRandom());

// 打印这个SSLContext实例使用的协议

System.out.println("缺省安全套接字使用的协议: " + s.getProtocol());

// 获取SSLContext实例相关的SSLEngine

SSLEngine e = s.createSSLEngine();

System.out

.println("支持的协议: " + Arrays.asList(e.getSupportedProtocols()));

System.out.println("启用的协议: " + Arrays.asList(e.getEnabledProtocols()));

System.out.println("支持的加密套件: "

+ Arrays.asList(e.getSupportedCipherSuites()));

System.out.println("启用的加密套件: "

+ Arrays.asList(e.getEnabledCipherSuites()));

}

运行结果如下:

点击在新窗口中浏览原图
CTRL+鼠标滚轮放大或缩小

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代码  


// 抛出异常  
// javax.net.ssl.SSLException: No available certificate or key corresponds  
// to the SSL cipher suites which are enabled.  
public static void notOk() throws IOException {  
    SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory  
            .getDefault();  
    SSLServerSocket server = (SSLServerSocket) factory  
            .createServerSocket(10000);  
    System.out.println("ok");  
    server.accept();  
}  

// 抛出异常

// javax.net.ssl.SSLException: No available certificate or key corresponds

// to the SSL cipher suites which are enabled.

public static void notOk() throws IOException {

SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory

.getDefault();

SSLServerSocket server = (SSLServerSocket) factory

.createServerSocket(10000);

System.out.println("ok");

server.accept();

}

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

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

点击在新窗口中浏览原图
CTRL+鼠标滚轮放大或缩小

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


Java代码  


// 启动一个ssl server socket  
// 配置了证书, 所以不会抛出异常  
public static void sslSocketServer() throws Exception {  
  
    // key store相关信息  
    String keyName = "cmkey";  
    char[] keyStorePwd = "123456".toCharArray();  
    char[] keyPwd = "123456".toCharArray();  
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());  
  
    // 装载当前目录下的key store. 可用jdk中的keytool工具生成keystore  
    InputStream in = null;  
    keyStore.load(in = Test2.class.getClassLoader().getResourceAsStream(  
            keyName), keyPwd);  
    in.close();  
  
    // 初始化key manager factory  
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory  
            .getDefaultAlgorithm());  
    kmf.init(keyStore, keyPwd);  
  
    // 初始化ssl context  
    SSLContext context = SSLContext.getInstance("SSL");  
    context.init(kmf.getKeyManagers(),  
            new TrustManager[] { new MyX509TrustManager() },  
            new SecureRandom());  
  
    // 监听和接收客户端连接  
    SSLServerSocketFactory factory = context.getServerSocketFactory();  
    SSLServerSocket server = (SSLServerSocket) factory  
            .createServerSocket(10002);  
    System.out.println("ok");  
    Socket client = server.accept();  
    System.out.println(client.getRemoteSocketAddress());  
  
    // 向客户端发送接收到的字节序列  
    OutputStream output = client.getOutputStream();  
  
    // 当一个普通 socket 连接上来, 这里会抛出异常  
    // Exception in thread "main" javax.net.ssl.SSLException: Unrecognized  
    // SSL message, plaintext connection?  
    InputStream input = client.getInputStream();  
    byte[] buf = new byte[1024];  
    int len = input.read(buf);  
    System.out.println("received: " + new String(buf, 0, len));  
    output.write(buf, 0, len);  
    output.flush();  
    output.close();  
    input.close();  
  
    // 关闭socket连接  
    client.close();  
    server.close();  
}  

// 启动一个ssl server socket

// 配置了证书, 所以不会抛出异常

public static void sslSocketServer() throws Exception {



// key store相关信息

String keyName = "cmkey";

char[] keyStorePwd = "123456".toCharArray();

char[] keyPwd = "123456".toCharArray();

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());



// 装载当前目录下的key store. 可用jdk中的keytool工具生成keystore

InputStream in = null;

keyStore.load(in = Test2.class.getClassLoader().getResourceAsStream(

keyName), keyPwd);

in.close();



// 初始化key manager factory

KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory

.getDefaultAlgorithm());

kmf.init(keyStore, keyPwd);



// 初始化ssl context

SSLContext context = SSLContext.getInstance("SSL");

context.init(kmf.getKeyManagers(),

new TrustManager[] { new MyX509TrustManager() },

new SecureRandom());



// 监听和接收客户端连接

SSLServerSocketFactory factory = context.getServerSocketFactory();

SSLServerSocket server = (SSLServerSocket) factory

.createServerSocket(10002);

System.out.println("ok");

Socket client = server.accept();

System.out.println(client.getRemoteSocketAddress());



// 向客户端发送接收到的字节序列

OutputStream output = client.getOutputStream();



// 当一个普通 socket 连接上来, 这里会抛出异常

// Exception in thread "main" javax.net.ssl.SSLException: Unrecognized

// SSL message, plaintext connection?

InputStream input = client.getInputStream();

byte[] buf = new byte[1024];

int len = input.read(buf);

System.out.println("received: " + new String(buf, 0, len));

output.write(buf, 0, len);

output.flush();

output.close();

input.close();



// 关闭socket连接

client.close();

server.close();

}

  4.2 SSLSocket

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

Java代码  


// 通过socket连接服务器  
public static void socket() throws UnknownHostException, IOException {  
    Socket s = new Socket("localhost", 10002);  
    System.out.println(s);  
    System.out.println("ok");  
  
    OutputStream output = s.getOutputStream();  
    InputStream input = s.getInputStream();  
  
    output.write("alert".getBytes());  
    System.out.println("sent: alert");  
    output.flush();  
  
    byte[] buf = new byte[1024];  
    int len = input.read(buf);  
    System.out.println("received:" + new String(buf, 0, len));  
}  

// 通过socket连接服务器

public static void socket() throws UnknownHostException, IOException {

Socket s = new Socket("localhost", 10002);

System.out.println(s);

System.out.println("ok");



OutputStream output = s.getOutputStream();

InputStream input = s.getInputStream();



output.write("alert".getBytes());

System.out.println("sent: alert");

output.flush();



byte[] buf = new byte[1024];

int len = input.read(buf);

System.out.println("received:" + new String(buf, 0, len));

}

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

点击在新窗口中浏览原图
CTRL+鼠标滚轮放大或缩小
服务器则抛出异常
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代码  


// 不使用证书, 通过ssl socket连接服务器  
// 抛出异常, 提示找不到证书  
public static void sslSocket() throws UnknownHostException, IOException {  
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory  
            .getDefault();  
    SSLSocket s = (SSLSocket) factory.createSocket("localhost", 10002);  
    System.out.println("ok");  
  
    OutputStream output = s.getOutputStream();  
    InputStream input = s.getInputStream();  
  
    output.write("alert".getBytes());  
    System.out.println("sent: alert");  
    output.flush();  
  
    byte[] buf = new byte[1024];  
    int len = input.read(buf);  
    System.out.println("received:" + new String(buf, 0, len));  
}  

// 不使用证书, 通过ssl socket连接服务器

// 抛出异常, 提示找不到证书

public static void sslSocket() throws UnknownHostException, IOException {

SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory

.getDefault();

SSLSocket s = (SSLSocket) factory.createSocket("localhost", 10002);

System.out.println("ok");



OutputStream output = s.getOutputStream();

InputStream input = s.getInputStream();



output.write("alert".getBytes());

System.out.println("sent: alert");

output.flush();



byte[] buf = new byte[1024];

int len = input.read(buf);

System.out.println("received:" + new String(buf, 0, len));

}

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

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

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

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

Java代码  


public static void sslSocket2() throws Exception {  
    SSLContext context = SSLContext.getInstance("SSL");  
               // 初始化  
    context.init(null,  
            new TrustManager[] { new Test2.MyX509TrustManager() },  
            new SecureRandom());  
    SSLSocketFactory factory = context.getSocketFactory();  
    SSLSocket s = (SSLSocket) factory.createSocket("localhost", 10002);  
    System.out.println("ok");  
  
    OutputStream output = s.getOutputStream();  
    InputStream input = s.getInputStream();  
  
    output.write("alert".getBytes());  
    System.out.println("sent: alert");  
    output.flush();  
  
    byte[] buf = new byte[1024];  
    int len = input.read(buf);  
    System.out.println("received:" + new String(buf, 0, len));  
}  

public static void sslSocket2() throws Exception {

SSLContext context = SSLContext.getInstance("SSL");

                // 初始化

context.init(null,

new TrustManager[] { new Test2.MyX509TrustManager() },

new SecureRandom());

SSLSocketFactory factory = context.getSocketFactory();

SSLSocket s = (SSLSocket) factory.createSocket("localhost", 10002);

System.out.println("ok");



OutputStream output = s.getOutputStream();

InputStream input = s.getInputStream();



output.write("alert".getBytes());

System.out.println("sent: alert");

output.flush();



byte[] buf = new byte[1024];

int len = input.read(buf);

System.out.println("received:" + new String(buf, 0, len));

}

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




程序猿的技术大观园:www.javathinker.net
  Java面向对象编程-->Swing组件(下)
  JavaWeb开发-->JSP技术详解(Ⅱ)
  JSP与Hibernate开发-->立即检索和延迟检索策略
  Java网络编程-->客户端协议处理框架
  精通Spring-->
  Vue3开发-->Vue简介
  Java设计模式: 里氏替换原则和合成复用原则详解
  Java 语言中十大“坑爹”功能!
  用注解去代替if-else的技巧
  内部类的种类和用法
  64匹马,8个赛道,找出跑得最快的4匹马
  Java异常堆栈信息以字符串形式输出
  NoClassDefFoundError和ClassNotFoundException的区别
  邀请您一起来祝福和祈祷,祈愿疫情早日消除,平安吉祥
  Synchronized与ReentrantLock区别总结
  Eclipse使用指南:工作空间(Workspace)
  用BigDecimal进行精确运算的范例
  java 支持分词的高性能拼音转换工具,速度是 pinyin4j 的两倍
  Java虚拟机(JVM)的内存结构
  Java入门实用代码:线程状态监测
  【Java 并发笔记】CountDownLatch 相关整理
  更多...
 IPIP: 已设置保密
楼主      
1页 0条记录 当前第1
发表一个新主题 开启一个新投票 回复文章


中文版权所有: JavaThinker技术网站 Copyright 2016-2026 沪ICP备16029593号-2
荟萃Java程序员智慧的结晶,分享交流Java前沿技术。  联系我们
如有技术文章涉及侵权,请与本站管理员联系。