SSL/TLS connection from Eclipse Paho Java client to mosquitto MQTT broker
By Sharon Ben Asher
Mosquitto is an Open Source MQTT v3.1 Broker written in C (http://mosquitto.org)
Eclipse Paho project has a Java MQTT client (http://eclipse.org/paho/)
The code snippet below demonstrates how to establish a secured connection from a Paho client to a mosquitto broker.
The connection includes server and client authentication through openssl (PEM formatted) certificates.
1) Follow the instructions on the mosquitto site to produce all the necessary certificates
2) Configure the broker to expect SSL connections.
3) On the client side, Paho has several options for specifying properties for the creation of SSL sockets
(Properties, JVM arguments, etc). However, none of them will work with mosquitto (historically, Paho worked with IBM brokers).
Fortunately, it also accepts a custom made instance of javax.net.ssl.SSLSocketFactory through the method MqttConnectOptions.setSocketFactory() and this works.
example code using Paho API to establish connection:
String serverUrl = "ssl://myMosquittoServer.com:1883";
MqttClient client = new MqttClient(serverUrl, "consumerId" , null);
MqttConnectOptions options = new MqttConnectOptions();
options.setSocketFactory(SslUtil.getSocketFactory("caFilePath", "clientCrtFilePath", "clientKeyFilePath", "password"));
The interesting bit is, of course, SslUtil.getSocketFactory() method. The code is attached seperately.
Since Java cannot read PEM formatted certificates, the method is using bouncy castle (http://www.bouncycastle.org/) to load the necessary files:
ca.crt is used to authenticate the server and is used to init an instance of javax.net.ssl.TrustManagerFactory.
client.crt/.key are sent to mosquitto for client authentication, and therefore are used to init an instance of javax.net.ssl.KeyManagerFactory.
The method expects all files as String full paths.
The method is using Files.readAllBytes() which is available in JDK 7.
basically, you need to load the file into byte array and pass that array to the constructor of ByteArrayInputStream as is demonstrated in the code.