ssl/tls encryption of Emqtt

Keywords: Programming SSL Java Eclipse Windows

After last week, it took two or three days this week to implement emqtt's ssl/tls encryption.

The main process is still referred to: https://blog.csdn.net/a704397849/article/details/88885198#commentsedit At the last step, when subscribing to messages with mosquitto_sub, there are always problems:

Contact the author of the reference article, and add QQ, unexpectedly is a very enthusiastic person. He went back to the process and was sure it was all right. He gave me a client code:

package com.zkong.mqttssl;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class MqttTLSTest {

    static MqttClientCallback mqttClientCallback = new MqttClientCallback();
    static MqttAsyncClient mqttClient = null;

    static String username = "stan";  //Note that you fill in your own mqtt password here
    static String password = "123456"; //Note that you fill in your own mqtt password here
    //String broker = tcp://xxx.xx.xxxx.xxxx:1883; //Note that you need to fill in the address of your mqtt server here.
    static String broker = "ssl://192.168.100.117:8883 "; // Note that you need to fill in the address of your mqtt server here.

    public static void main(String[] args) throws InterruptedException {
        start();
        while (true){
            Thread.sleep(10000);
        }
    }

    public static void start() {
        String clientId = "mqttserver" + String.valueOf(System.currentTimeMillis());

        try {
            mqttClient = new MqttAsyncClient(broker, clientId, new MemoryPersistence());
            mqttClient.setCallback(mqttClientCallback);

            //Subscribe to connect to mqtt server
            subscribeConnect();

            //Publish Connect to mqtt Server
            //Slightly

        } catch (MqttException me) {
            System.out.println("reason " + me.getReasonCode());
            System.out.println("msg " + me.getMessage());
            System.out.println("loc " + me.getLocalizedMessage());
            System.out.println("cause " + me.getCause());
            System.out.println("excep " + me);
            me.printStackTrace();
        }
    }

    public static void subscribeConnect() {
        System.out.println("Subscription connection");
        if (mqttClient != null) {
            try {
                MqttConnectOptions connOpts = new MqttConnectOptions();

                connOpts.setCleanSession(true);
                connOpts.setMaxInflight(100000);

                connOpts.setUserName(username);
                connOpts.setPassword(password.toCharArray());

                //ssl connection, where TrustManager is self-implemented, without the certificate to verify the server
                TrustManager[] trustAllCerts = new TrustManager[1];
                TrustManager tm = new MyTM();
                trustAllCerts[0] = tm;
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, null);
                SocketFactory factory = sc.getSocketFactory();
                connOpts.setSocketFactory(factory);
                //

                mqttClient.connect(connOpts, null, new IMqttActionListener() {
                    @Override
                    public void onSuccess(IMqttToken asyncActionToken) {
                        try {
                            //Subscribe to topic for test messages, message quality 1
                            mqttClient.subscribe("test", 1);
                        } catch (MqttException me) {
                            System.out.println("reason " + me.getReasonCode());
                            System.out.println("msg " + me.getMessage());
                            System.out.println("loc " + me.getLocalizedMessage());
                            System.out.println("cause " + me.getCause());
                            System.out.println("excep " + me);
                            me.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                        System.out.println("mqtt No connection:" + exception.getMessage());
                        exception.printStackTrace();
                    }
                });
            } catch (MqttException me) {
                System.out.println("reason " + me.getReasonCode());
                System.out.println("msg " + me.getMessage());
                System.out.println("loc " + me.getLocalizedMessage());
                System.out.println("cause " + me.getCause());
                System.out.println("excep " + me);
                me.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            }
        }
    }

    //MyTM is a self-implemented certification management class, which returns true if it has a certificate from the verification server. It will be successful forever! _________.
    static class MyTM implements TrustManager, X509TrustManager {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(X509Certificate[] certs) {
            return true;
        }

        @Override
        public void checkServerTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {
            return;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] certs, String authType)
                throws CertificateException {
            return;
        }
    }

    public static class MqttClientCallback implements MqttCallback{

        @Override
        public void connectionLost(Throwable arg0)
        {
            System.out.println("mqtt Lost connection");
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken arg0)
        {
            System.out.println("mqtt Send completed!");
        }

        @Override
        public void messageArrived(String topic, MqttMessage message)
                throws Exception
        {
            String content = new String(message.getPayload(), "utf-8");
            System.out.println("Received mqtt news,topic: "+topic+" ,content: "+content);
        }
    }
}

There is no problem subscribing to messages with this client code, because my server has opened mysql-based authentication, so it must provide username and password.

To be thorough, it is estimated that a clean machine must be found to reinstall emqtt.

Some questions are recorded here:

About mosquitto

Like emqtt, it is also a broker of mqtt itself. It exists as a service after being installed on windows. When it is in startup state, it will occupy 1883 ports and cause emqtt not to start completely. It can be shut down in Windows service management.

Install openssl on Centos7

https://www.cnblogs.com/rxbook/p/9367725.html

Install mosquitto on Centos7

https://blog.csdn.net/xj178926426/article/details/78832296

 

Not through the process:

Two-way authentication: https://blog.csdn.net/zljintan/article/details/83619309

With certificate validation (using MQTTBox as the client): https://www.cnblogs.com/lexiaofei/p/8403995.html

Posted by tomtimms on Tue, 01 Oct 2019 17:31:00 -0700