public
Last active

SSL/TLS connection from Eclipse Paho Java client to mosquitto MQTT broker

  • Download Gist
SslUtil.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
import java.io.*;
import java.nio.file.*;
import java.security.*;
import java.security.cert.*;
import javax.net.ssl.*;
 
import org.bouncycastle.jce.provider.*;
import org.bouncycastle.openssl.*;
 
public class SslUtil
{
static SSLSocketFactory getSocketFactory (final String caCrtFile, final String crtFile, final String keyFile,
final String password) throws Exception
{
Security.addProvider(new BouncyCastleProvider());
 
// load CA certificate
PEMReader reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))));
X509Certificate caCert = (X509Certificate)reader.readObject();
reader.close();
 
// load client certificate
reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile)))));
X509Certificate cert = (X509Certificate)reader.readObject();
reader.close();
 
// load client private key
reader = new PEMReader(
new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile)))),
new PasswordFinder() {
@Override
public char[] getPassword() {
return password.toCharArray();
}
}
);
KeyPair key = (KeyPair)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);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(caKs);
 
// client key and certificates are sent to server so it can authenticate us
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
ks.setCertificateEntry("certificate", cert);
ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(), new java.security.cert.Certificate[]{cert});
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(ks, password.toCharArray());
 
// finally, create SSL socket factory
SSLContext context = SSLContext.getInstance("TLSv1");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
 
return context.getSocketFactory();
}
}
readme.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
SSL/TLS connection from Eclipse Paho Java client to mosquitto MQTT broker
 
By Sharon Ben Asher
AVG Mobilation
Sharon.Ben-Asher@AVG.com
 
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
http://mosquitto.org/man/mosquitto-tls-7.html
 
2) Configure the broker to expect SSL connections.
example configuration:
listener 1883
cafile /home/ubuntu/etc/ca.crt
certfile /home/ubuntu/etc/server.crt
keyfile /home/ubuntu/etc/server.key
require_certificate true
use_identity_as_username true
 
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);
client.setCallback(new MyCallback());
MqttConnectOptions options = new MqttConnectOptions();
options.setConnectionTimeout(60);
options.setKeepAliveInterval(60);
options.setSocketFactory(SslUtil.getSocketFactory("caFilePath", "clientCrtFilePath", "clientKeyFilePath", "password"));
client.connect(options);
client.subscribe("topic", 0);
 
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.

exception throwing after line :KeyPair key = (KeyPair)reader.readObject();

org.bouncycastle.openssl.PEMException: problem parsing ENCRYPTED PRIVATE KEY: javax.crypto.BadPaddingException: pad block corrupted
at org.bouncycastle.openssl.PEMReader$EncryptedPrivateKeyParser.parseObject(Unknown Source)
at org.bouncycastle.openssl.PEMReader.readObject(Unknown Source)
at org.eclipse.paho.sample.mqttv3app.SslUtil.getSocketFactory(SslUtil.java:38)
at org.eclipse.paho.sample.mqttv3app.Sample.(Sample.java:194)
at org.eclipse.paho.sample.mqttv3app.Sample.main(Sample.java:137)
Caused by: javax.crypto.BadPaddingException: pad block corrupted

from this post
http://stackoverflow.com/questions/14054593/aes-decryption-javax-crypto-badpaddingexception-pad-block-corrupted-in-android
it seems like this is either an encoding problem or perhaps corrupted certificate file? if the client is in Windows it might be new-line character problem

Hi sharonbn,

I have added above class file into my package but i am unable to use this class from my Sample.java(paho) file.

conOpt.setSocketFactory(SslUtil.getSocketFactory(CA_CERT_PATH,CLIENT_CERT_PATH,CLIENT_KEY_PATH, PASSWORD));

I am getting following error:
src/org/eclipse/paho/sample/mqttv3app/Sample.java:195: error: cannot find symbol
conOpt.setSocketFactory(SslUtil.getSocketFactory(CA_CERT_PATH,CLIENT_CERT_PATH, CLIENT_KEY_PATH, PASSWORD));
^
symbol: variable SslUtil
location: class Sample
1 error

Hi sharonbn,

Can you provide steps to compile java paho client after adding SslUtil.java , i am using ant tool to compile paho client as given in link:
http://mobilave.info/blog/2012/Quick_start_guide_for_the_Paho_MQTT_Java_Client.html.

Thanks,
Tushar

Hi sharonbn,

i am getting following error when compiling Sample.java

javac -cp /home/tushar/new_jar_paho/bcpkix-jdk15on-148.jar:/home/tushar/new_jar_paho/bcprov-jdk15on-148.jar:/home/tushar/new_jar_paho/nio_framework-1.1beta_all.jar:/tmp/Mqttv3ClientOut/ship/org.eclipse.paho.client.mqttv3.jar src/org/eclipse/paho/sample/mqttv3app/Sample.java

Note: src/org/eclipse/paho/sample/mqttv3app/Sample.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

Thanks,
Tushar

Hi,

I am trying to use paho library to connect to an ActiveMQ mqtt broker, I have followed the steps on the ActiveMQ site to generate some self signed certifcates, keystore files and some trust store files. I am not quite sure how all of them translate to the input for this class. as i don't have a caCertifcate and private key file. can I generate them using java "keytool" Any help would be really appreciated as I am really new to this and don't quite understand what i need to provide. All I am trying use the SSL for is the encryption and i don't really need to client authentication and I can blindly trust the server.

Thanks in advance,

Z

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.