Android Code Snippet [B4X] MQTT SSL and Self Signed Certificates

There are two client libraries: jMQTT for B4A and B4J and iMQTT for B4i. Both libraries support SSL connections. You just need to change the URI scheme to ssl:// instead of tcp://:
B4X:
mqtt.Initialize("mqtt", "ssl://127.0.0.1:17178", clientId)

If the broker is using a self signed certificate then you need to configure the client to accept all certificates.

B4A / B4J:
B4X:
Dim mo As MqttConnectOptions
mo.Initialize(user, password)
TrustAll(mo)
mqtt.Connect2(mo)

'Depends on JavaObject and jNet or Net libraries
Sub TrustAll (mo As MqttConnectOptions)
   Dim SSLContext As JavaObject
   SSLContext = SSLContext.InitializeStatic("javax.net.ssl.SSLContext").RunMethod("getInstance", Array("TLS"))
   Dim tm As CustomTrustManager
   tm.InitializeAcceptAll
   SSLContext.RunMethod("init", Array(Null, tm, Null))
   Dim jmo As JavaObject = mo
   jmo.RunMethod("setSocketFactory", Array(SSLContext.RunMethod("getSocketFactory", Null)))
End Sub

In B4i you need to set the new TrustAllCertificates property (iMQTT v1.10+):
B4X:
mo.TrustAllCertificates = True

If you are using jMQTTBroker2 then you can configure it to run over SSL:
B4X:
broker.Initialize("", 0) 'set the non-SSL port to 0
broker.SetUserAndPassword("user", "111") '(optional) set the username and password
Dim jo As JavaObject = broker
Dim config As JavaObject = jo.GetFieldJO("config")
config.RunMethod("setProperty", Array("ssl_port", "17178"))
config.RunMethod("setProperty", Array("key_manager_password", "123456"))
config.RunMethod("setProperty", Array("key_store_password", "123456"))
config.RunMethod("setProperty", Array("jks_path", "C:\Users\H\Downloads\keystore")) 'path to keystore file
broker.Start
Follow these instructions to create a self signed certificate: https://www.eclipse.org/jetty/docum...sl.html#generating-key-pairs-and-certificates
 
Top