1. 程式人生 > >mqtt mosquitto tls java 客戶端

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();
    }
}