mqtt mosquitto tls java 客戶端

物聯網交流羣:651219170

簡介

做爲 mosquitto 開啓 tls 之後的調試客戶端寫的代碼。其中需要注意的是
tls 的 ca 證書,如果你是自己ca那麼你要把他加到信任的 ca 列表,也就是下面那幾步。如果是真正的著名的 ca 頒佈的那麼可以把下面幾行代碼註釋掉。因爲jdk的jdk1.8/jre/lib/security/cacerts 裏面已經默認存了這寫著名機構的 ca.crt 了。

   public class SSLUtil
{

    /**
     * 獲取 tls 安全套接字工廠
     * @param caCrtFile null:使用系統默認的 ca 證書來驗證。 非 null:指定使用的 ca 證書來驗證服務器的證書。
     * @return tls 套接字工廠
     * @throws Exception
     */
    public static SSLSocketFactory getSocketFactory (final String caCrtFile) throws NoSuchAlgorithmException, IOException, KeyStoreException, CertificateException, KeyManagementException {
        Security.addProvider(new BouncyCastleProvider());


        //===========加載 ca 證書==================================
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        if( null != caCrtFile ){
            // 加載本地指定的 ca 證書
            PEMReader reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))));
            X509Certificate caCert = (X509Certificate)reader.readObject();
            reader.close();

            // CA certificate is used to authenticate server
            KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
            caKs.load(null, null);
            caKs.setCertificateEntry("ca-certificate", caCert);
            // 把ca作爲信任的 ca 列表,來驗證服務器證書
            tmf.init(caKs);
        }else {
            //使用系統默認的安全證書
            tmf.init((KeyStore)null);
        }

        // ============finally, create SSL socket factory==============
        SSLContext context = SSLContext.getInstance("TLSv1");
        context.init(null,tmf.getTrustManagers(), null);

        return context.getSocketFactory();
    }
}    

正式代碼:

1.增加依賴包

        <dependency>
            <groupId>org.eclipse.paho</groupId>
            <artifactId>mqtt-client</artifactId>
            <version>0.4.0</version>
        </dependency>

        <dependency>
            <groupId>bouncycastle</groupId>
            <artifactId>bcprov-jdk15</artifactId>
            <version>140</version>
        </dependency>

Service.java


/**
 * Created by yhy on 17-7-5.
 */

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


public class Server {

    public static final String caCrtFile = "/home/yhy/IdeaProjects/mqtt/src/main/resources/ca.crt";
    public static final String HOST = "ssl://iot.51awifi.com:1885";

    public static final String TOPIC = "/hello/tls";
    private static final String clientid ="server";

    private MqttClient client;
    private MqttTopic topic;
    private String userName = "yuhaiyang";
    private String passWord = "yuhaiyang";

    private MqttMessage message;

    public Server() throws MqttException {
        //MemoryPersistence設置clientid的保存形式,默認爲以內存保存
        client = new MqttClient(HOST, clientid, new MemoryPersistence());
    }

    private void connect() throws Exception {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(false);
        options.setUserName(userName);
        options.setPassword(passWord.toCharArray());


        options.setSocketFactory(SSLUtil.getSocketFactory(caCrtFile));

        // 設置超時時間
        options.setConnectionTimeout(10);
        // 設置會話心跳時間
        options.setKeepAliveInterval(60);
        try {
            client.setCallback(new PushCallback());
            client.connect(options);
            topic = client.getTopic(TOPIC);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void publish(MqttMessage message) throws MqttException{
        MqttDeliveryToken token = topic.publish(message);
        System.out.println("等待發送成功:"+token.isComplete());
        token.waitForCompletion();
        System.out.println("已經發送成功:"+token.isComplete());
    }

    public void subscription() throws MqttException {
        client.subscribe("#",2);
    }
    public static void main(String[] args) throws Exception {
        Server server =  new Server();
        server.connect();
        server.message = new MqttMessage();
        server.message.setQos(1);
        server.message.setRetained(true);
        server.message.setPayload("hello tls".getBytes());

        server.subscription();
        System.out.println("訂閱成功");

        server.publish(server.message);
        System.out.println("發佈成功");

        Thread.sleep(10000);


    }

}


class PushCallback implements MqttCallback {

    public void connectionLost(Throwable cause) {
        // 連接丟失後,一般在這裏面進行重連
        System.out.println("連接斷開,可以做重連");
    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        // subscribe後得到的消息會執行到這裏面
        System.out.println("接收消息主題:" + topic);
        System.out.println("接收消息Qos:" + mqttMessage.getQos());
        System.out.println("接收消息內容:" + new String(mqttMessage.getPayload()));
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        // 當下發成功被調用。
        System.out.println("deliveryComplete:" + iMqttDeliveryToken.isComplete());
    }

}
package com.awifi.athena.devicebus.common.ssl;

/**
 * Created by yhy on 17-7-5.
 */

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMReader;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class SSLUtil
{

    /**
     * 獲取 tls 安全套接字工廠
     * @param caCrtFile null:使用系統默認的 ca 證書來驗證。 非 null:指定使用的 ca 證書來驗證服務器的證書。
     * @return tls 套接字工廠
     * @throws Exception
     */
    public static SSLSocketFactory getSocketFactory (final String caCrtFile) throws NoSuchAlgorithmException, IOException, KeyStoreException, CertificateException, KeyManagementException {
        Security.addProvider(new BouncyCastleProvider());


        //===========加載 ca 證書==================================
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        if( null != caCrtFile ){
            // 加載本地指定的 ca 證書
            PEMReader reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))));
            X509Certificate caCert = (X509Certificate)reader.readObject();
            reader.close();

            // CA certificate is used to authenticate server
            KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
            caKs.load(null, null);
            caKs.setCertificateEntry("ca-certificate", caCert);
            // 把ca作爲信任的 ca 列表,來驗證服務器證書
            tmf.init(caKs);
        }else {
            //使用系統默認的安全證書
            tmf.init((KeyStore)null);
        }

        // ============finally, create SSL socket factory==============
        SSLContext context = SSLContext.getInstance("TLSv1");
        context.init(null,tmf.getTrustManagers(), null);

        return context.getSocketFactory();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章