证书认证理解:
https://juejin.cn/post/6844903953407148045
双向认证实现:
https://blog.51cto.com/u_4925054/1949641
单项认证实现:
public class HttpsUtil {
/**
* 对所有站点的信任
*
* @return SSLSocketFactory工厂对象
*/
public static SSLSocketFactory initSSLSocketFactory(Context context) {
//创建加密上下文
SSLContext sslContext = null;
CertificateFactory certificateFactory = null;
InputStream inputStream = null;
Certificate cer = null;
KeyStore keystore = null;
TrustManagerFactory trustManagerFactory = null;
try {
certificateFactory = CertificateFactory.getInstance("X.509");
inputStream = context.getAssets().open("6062391_www.kjgwzx.cn_public.crt");//这里导入SSL证书文件
try {
cer = certificateFactory.generateCertificate(inputStream);
} finally {
inputStream.close();
}
//创建一个证书库,并将证书导入证书库
keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(null, null); //双向验证时使用
keystore.setCertificateEntry("trust", cer);
// 实例化信任库
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keystore);
//这里要与服务器的算法类型保持一致TSL/SSL
sslContext = SSLContext.getInstance("TLS");
// sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
return sslContext.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
// try {
// //这里要与服务器的算法类型保持一致TSL/SSL
// sslContext = SSLContext.getInstance("TLS");
// sslContext = SSLContext.getInstance("SSL");
// X509TrustManager[] xTrustArray = new X509TrustManager[]
// {initTrustManager()};
// sslContext.init(null,
// xTrustArray, new SecureRandom());
// } catch (Exception e) {
// e.printStackTrace();
// }
return sslContext.getSocketFactory();
}
/**
* 生成TrustManager信任管理器类
*
* @return X509TrustManager
*/
public static X509TrustManager initTrustManager() {
// TrustManager[] mTrustManager = new TrustManager[]{new X509TrustManager() {
//
// @Override
// public X509Certificate[] getAcceptedIssuers() {
// return null;
// }
//
// @Override
// public void checkServerTrusted(X509Certificate[] arg0, String arg1)
// throws CertificateException {
//
// }
//
// @Override
// public void checkClientTrusted(X509Certificate[] arg0, String arg1)
// throws CertificateException {
//
// }
// }};
//信任所有证书 (官方不推荐使用)
X509TrustManager mTrustManager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[]{};
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
};
return mTrustManager;
}