<p><iframe name="ifd" src="https://mnifdv.cn/resource/cnblogs/ZLIOTB/CH395Q/my.html" frameborder="0" scrolling="auto" width="100%" height="1500"></iframe></p>
说明
这节说明一下设备使用SSL单向认证连接服务器以后检验一下服务器的证书.
这节就在下面的章节程序上进行修改
把这节里面的MyX509TrustManager.java 文件放到工程里面
在工程上点击鼠标右键,新建一个assets
导入证书
1.把mqtt服务器上面的cert.pem 证书下载到本地(该证书用于解开服务器证书)
2.复制证书
3.粘贴证书
使用证书
1.新建一个变量,用来选择验不验证证书
2.增加下面的函数
//拿到自己的证书 X509Certificate getX509Certificate(ClassLoader classLoader) throws IOException, CertificateException { InputStream in = classLoader.getResourceAsStream("assets/cert.pem"); // InputStream in = context.getAssets().open("cert.pem"); CertificateFactory instance = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) instance.generateCertificate(in); return certificate; }
下面这个地方要对应哈
3.把原先的程序改一下
4.把下面的程序放到else里面
try{ //SSLContext 初始化 SSLContext tls = SSLContext.getInstance("TLS"); String defaultType = KeyStore.getDefaultType(); KeyStore instance = KeyStore.getInstance(defaultType); instance.load(null); instance.setCertificateEntry("cert",getX509Certificate(MyMqttClient.class.getClassLoader())); String defaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();//得到默认算法 TrustManagerFactory trustMF = TrustManagerFactory.getInstance(defaultAlgorithm); trustMF.init(instance); TrustManager[] trustManagers = trustMF.getTrustManagers(); tls.init(null,trustManagers,new SecureRandom()); //ssl工厂 SSLSocketFactory socketFactory = tls.getSocketFactory(); mqttConnectOptions.setSocketFactory(socketFactory); Log.e(TAG, "InitMqttOptions: useSSLCheck Init"); }catch (Exception e){ Log.e(TAG, "InitMqttOptions: "+e ); }