sslcontext
- 什么是SSLSocket
(1)JDK文档指出,SSLSocket扩展Socket并提供使用SSL或TLS协议的安全套接字。
(2)这种套接字是正常的流套接字,但是它们在基础网络传输协议(如TCP)上添加了安全保护层。 - SSLContext的实现
(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证书,验证远程安全套接字 - SSLContext的使用
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())); }
SSLContext.getProtocol(): 返回当前SSLContext对象的协议名称
SSLContext.init(): 初始化当前SSLContext对象。 三个参数均可以为null。 详见JDK文档。
SSLEngine.getSupportedProtocols()等几个方法可以返回些 Engine上支持/已启用的协议、支持/已启用的加密套件 - 服务端代码
// 启动一个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(); }
- 各种方式链接服务器
5.1 普通socket链接
客户端的错误是接收到乱码。// 通过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)); }
服务器则抛出异常:javax.NET.ssl.SSLException: Unrecognized SSL message, plaintext connection?
5.2 改成SSLSocket, 但是不使用证书。
程序客户在不持有证书的情况下直接进行连接,服务器端会产生运行时异常javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown,不允许进行连接。 我们可以指定像下面这样执行客户端,服务器端可以成功echo客户端的发出的字符串"alert"// 不使用证书, 通过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)); }
5.3 改成SSLSocket, 对SSLContext进行如下初始化。Java -Djavax.Net.ssl.trustStore=cmkey Client
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)); }
个人例子java创建https,http请求HttpClient
- https
javax.net.ssl.SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); CloseableHttpClient build = HttpClients.custom().setSSLSocketFactory(sslsf).build(); return build; ```
- http
HttpClientBuilder create = HttpClientBuilder.create(); create.addInterceptorFirst(new SpiderRequestUserAgent()); create.addInterceptorFirst(new SpiderRequestContentType()); CloseableHttpClient build = create.build();