Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
SSL/TLS connection from Eclipse Paho Java client to mosquitto MQTT broker
SSL/TLS connection from Eclipse Paho Java client to mosquitto MQTT broker
By Sharon Ben Asher
AVG Mobilation
Mosquitto is an Open Source MQTT v3.1 Broker written in C (
Eclipse Paho project has a Java MQTT client (
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.
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 through the method MqttConnectOptions.setSocketFactory() and this works.
example code using Paho API to establish connection:
String serverUrl = "ssl://";
MqttClient client = new MqttClient(serverUrl, "consumerId" , null);
client.setCallback(new MyCallback());
MqttConnectOptions options = new MqttConnectOptions();
options.setSocketFactory(SslUtil.getSocketFactory("caFilePath", "clientCrtFilePath", "clientKeyFilePath", "password"));
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 ( to load the necessary files:
ca.crt is used to authenticate the server and is used to init an instance of
client.crt/.key are sent to mosquitto for client authentication, and therefore are used to init an instance of
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.
import java.nio.file.*;
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();
// load client certificate
reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile)))));
X509Certificate cert = (X509Certificate)reader.readObject();
// load client private key
reader = new PEMReader(
new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile)))),
new PasswordFinder() {
public char[] getPassword() {
return password.toCharArray();
KeyPair key = (KeyPair)reader.readObject();
// 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());
// 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[]{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();

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(
at org.eclipse.paho.sample.mqttv3app.Sample.(
at org.eclipse.paho.sample.mqttv3app.Sample.main(
Caused by: javax.crypto.BadPaddingException: pad block corrupted


sharonbn commented Jan 7, 2013

from this post
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 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/ 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 , i am using ant tool to compile paho client as given in link:


Hi sharonbn,

i am getting following error when compiling

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/

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

Note: Recompile with -Xlint:deprecation for details.



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,


anemethy commented Apr 2, 2015

Is there an update on this ??? The code is 2 years old and all of the bouncy castle libraries have changed. Please advise. Regards

I've written similar code using a newer version of the BouncyCastle library. Those looking for an update to this, check out

Thank you! Exactly what I was looking for :) Much Karma going your way.

sadaf13 commented Feb 3, 2016

Hey!! i tried the above solution but facing the following exception.

Exception in thread "main" MqttException (0) - Received fatal alert: handshake_failure
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(
at org.eclipse.paho.client.mqttv3.internal.ClientComms$
Caused by: Received fatal alert: handshake_failure
at org.eclipse.paho.client.mqttv3.internal.SSLNetworkModule.start(
at org.eclipse.paho.client.mqttv3.internal.ClientComms$
... 1 more

hey,I am facing following exception:
The specified SocketFactory type does not match the broker URI (32105)
at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.createNetworkModule(
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.createNetworkModules(
at org.eclipse.paho.client.mqttv3.MqttAsyncClient.connect(
at org.eclipse.paho.client.mqttv3.MqttClient.connect(
at com.ei.paho.client.subscriber.SslSubscriber.start(
at com.ei.paho.client.subscriber.SslSubscriber.main(

@sadaf13 Were you able to get past that issue?
I'm getting the exact same exception. If yes, can you suggest me what you had to do to get around it?

@dishraval I am getting exact same exception trace. Did you find any solution for the issue The specified SocketFactory type does not match the broker URI (32105)?

wendyhi commented Apr 27, 2016

In my case, changing the url of the mqtt server from tcp:// to ssl:// resolve the issue about
The specified SocketFactory type does not match the broker URI (32105)

Hello, I am trying to connect to AWS iot using Paho Mqtt Java Client. I have to specify the client_id, but also configure the connection tls_set meaning that I will specify root certificate (.crt), certificate file (.pem.crt) and the private key (.pem.crt) . I have already implemented this on Python, but unfortunately I need it in Java. Is there anyway you could help me ? The URI that I have is an endpoint from Amazon like :

How can I specify this in my code ??! Any kind of help would be appreciated. Thank you !!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment