Android客户端通过Paho MQTT和Broker建立SSL/TLS的单向连接

MQTT是物联网时代的基础通讯协议。Paho Mqtt Client是android应用开发中广泛使用的Mqtt Client库。为了确保通讯安全,通常会使用SSL来进行通讯的加密。

Paho Mqtt Client官网上并没有详细说明解释如何建立SSL/TLS连接,下面记录一下。

1 生成证书

网上的说明很多,重点是要转换成BKS格式的证书。
我参考的是下面的链接:http://www.steves-internet-guide.com/mosquitto-tls/

转换BKS格式的步骤

  • 到https://www.bouncycastle.org/latest_releases.html下载bcprov-jdk15on-159.jar
  • 将jar放到JDK或者JRE目录下的/lib/ext中
  • 运行命令
    keytool -importcert -keystore mqtt_server.bks -file ca.crt -storetype BKS -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider
    • mqtt_server.bks,要生成BKS格式的证书
    • ca.crt是按照#1步骤生成的证书
  • 如果碰到java.lang.ClassNotFoundException: org.bouncycastle.jce.provider.BouncyCastleProvider的错误,那就是bcprov-jdk15on-159.jar没有放到正确的目录去。解决方法:首先确认一下使用的keytool是在JDK还是JRE的目录下,如果keytool是在jdk下,就将bcprov-jdk15on-159.jar复制jdk的lib/ext下,如果是在jre的下,就复制到JRE的lib/ext目录下。
  • 生成的BKS证书要放到Android项目的res/raw下

2 引用Paho Mqtt Client库

按照Paho Mqtt Client在github上的说明就可以完成,别忘了在AndroidManifest.xml中声明mqttservice。

    
    

3 具体的代码

直接上代码

private void doStartMqttClient() {
    if (mMqttClient == null) {
        initMqttClient();
    }

    mMqttClient.setCallback(mCallback);
    try {
        mMqttClient.connect(mMqttConnectionOptions, null, mqttActionListener);
    } catch (MqttException e) {
        e.printStackTrace();
    }
}

private void initMqttClient() {
    mMqttClient = new MqttAndroidClient(this.getApplicationContext(), 
                                            Constants.SSL_URL, getClientId());
    mMqttConnectionOptions = new MqttConnectOptions();
    mMqttConnectionOptions.setCleanSession(true);
    mMqttConnectionOptions.setAutomaticReconnect(false);
    mMqttConnectionOptions.setUserName(Constants.USER_NAME);
    mMqttConnectionOptions.setPassword(Constants.PASSWORD.toCharArray());
    SocketFactory socketFactory = getSocketFactory();
    mMqttConnectionOptions.setSocketFactory(socketFactory);
}

private SocketFactory getSocketFactory() {
    try {
        SSLContext context;
        KeyStore ts = KeyStore.getInstance("BKS");
        ts.load(getResources().openRawResource(R.raw.mqtt_server),
                   Constants.CACRT_PASSWORD.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(ts);
        TrustManager[] tm = tmf.getTrustManagers();
        context = SSLContext.getInstance("TLS");
        context.init(null, tm, null);

        return context.getSocketFactory();
    } catch (Exception e) {
        Log.e(TAG, "", e);
        notifyActivity(e.getLocalizedMessage());
        return null;
    }
}

MqttCallbackExtended mCallback = new MqttCallbackExtended() {
    @Override
    public void connectComplete(boolean reconnect, String serverURI) {
        notifyActivity("连接成功!");
    }

    @Override
    public void connectionLost(Throwable cause) {
        notifyActivity("connectionLost");
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) {
        notifyActivity("收到消息!");
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        notifyActivity("发送完成!");
    }
};

private static class MqttActionListener implements IMqttActionListener {
    WeakReference mService;

    MqttActionListener(ModuleService service) {
        mService = new WeakReference<>(service);
    }

    @Override
    public void onSuccess(IMqttToken asyncActionToken) {
        ModuleService service = mService.get();
        if (service != null) {
            service.setStatus(STATUS_CONNECTED);
            service.doSubscribeTopic();
            service.mHandler.sendEmptyMessage(MSG_ONLINE);
        }
    }

    @Override
    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
        ModuleService service = mService.get();
        if (service != null) {
            service.setStatus(STATUS_CONNECT_FAIL);
            service.mHandler.sendEmptyMessage(MSG_CONN_FAIL);
            Log.e(TAG, "", exception);
            service.notifyActivity(exception.getLocalizedMessage());
        }
    }
}

你可能感兴趣的:(Android客户端通过Paho MQTT和Broker建立SSL/TLS的单向连接)