一、说明
笔记主要是记录一些本人在开发当中的学习和使用笔记。笔记内容包含一些本人觉得重要的知识点、本人易犯的错误等。
由于本人水平有限,其中出现的错误或者不合理的地方望各位读者多多包含,并指出其中不合理和错误的地方,以便我来修正。谢谢!
二、笔记时间
2018年10月17日
三、简述
本文主要讲述SSLSocket的简单使用方式。
四、详情
SSLSocket是Socekt的加密通讯模式。本文介绍无证书实现SSLSocket的方式。
第一:重写X509TrustManager,使信任所有证书。如下代码:
package com.test.sys.plcd.util;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
/**
* 创建人: lipy
* 创建时间: 2018/4/23
* 修改人:lipy
* 修改时间:2018/4/23
* 修改内容:
*
* 功能描述: 信任所有证书
*/
public class MyX509TrustManager implements X509TrustManager {
public MyX509TrustManager() throws Exception {
}
/*
* Delegate to the default trust manager.
*/
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
/*
* Delegate to the default trust manager.
*/
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
/*
* Merely pass this through.
*/
public X509Certificate[] getAcceptedIssuers() {
// return new java.security.cert.X509Certificate[0];
return null;
}
}
第二:创建SSLSocket。如下代码:
//java
import java.io.IOException;
import java.net.UnknownHostException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
try {
TrustManager[] tm = new TrustManager[]{new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSLv3");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocket sslSocket = sslContext.getSocketFactory().createSocket(mHost, mPort);
} catch (UnknownHostException e) {
} catch (IOException e) {
} catch (Exception e) {
}
//kotlin
import java.io.IOException;
import java.net.UnknownHostException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
try {
val tm = arrayOf<TrustManager>(MyX509TrustManager())
val sslContext = SSLContext.getInstance("SSLv3")
sslContext.init(null, tm, java.security.SecureRandom())
val mSllSocket = sslContext.socketFactory.createSocket(mHost, mPort) as SSLSocket?
} catch (e: UnknownHostException) {
} catch (e: IOException) {
} catch (e: Exception) {
}