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://:
mqtt.Initialize("mqtt", "ssl://", clientId)

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

B4A / B4J:
Dim mo As MqttConnectOptions
mo.Initialize(user, password)

'Depends on JavaObject and jNet or Net libraries
Sub TrustAll (mo As MqttConnectOptions)
   Dim SSLContext As JavaObject
   SSLContext = SSLContext.InitializeStatic("").RunMethod("getInstance", Array("TLS"))
   Dim tm As CustomTrustManager
   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+):
mo.TrustAllCertificates = True

If you are using jMQTTBroker2 then you can configure it to run over SSL:
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
Follow these instructions to create a self signed certificate: