#Region Project Attributes
#MainFormWidth: 600
#MainFormHeight: 600
#End Region
Sub Process_Globals
Private fx As JFX
Private MainForm As Form
Dim client As MqttClient
Private Button_connect As Button
End Sub
Sub AppStart (Form1 As Form, Args() As String)
MainForm = Form1
MainForm.RootPane.LoadLayout("Layout1") 'Load the layout file.
MainForm.Show
'Initial cmqtt client
client.Initialize("client", "tcp://192.168.1.10:1883", "myClientName")
'setup Paho MqttCallbackExtended
Dim Mjo As JavaObject = client
Dim event As Object = Mjo.CreateEventFromUI("org.eclipse.paho.client.mqttv3.MqttCallback", "MqttCallback", Null)
Mjo.GetFieldJO("client").RunMethod("setCallback", Array(event))
'set Paho Keep avlive & Timeout
Dim mo As MqttConnectOptions
mo.Initialize("user","pass")
Dim result As String
Dim MqttConnectOptions1 As JavaObject = mo
result = MqttConnectOptions1.RunMethod("setKeepAliveInterval",Array(60))
result = MqttConnectOptions1.RunMethod("setConnectionTimeout",Array(60))
'setup SocketFactory => does not work
Dim jo As JavaObject = Me
jo.InitializeNewInstance("b4j.example.main.SslUtil", Array(Null))
Log(jo.RunMethod("setSocketFactory",jo.RunMethod("getSocketFactory", Array As String (File.GetUri(File.DirAssets, "root_ca_auth.cer"), File.GetUri(File.DirAssets, "sensor_auth.crt"), File.GetUri(File.DirAssets, "sensor_auth.key"), "pass"))))
'result = MqttConnectOptions1.RunMethod("setSocketFactory",input from SslUtil)
End Sub
private Sub MqttCallback_Event (MethodName As String, Args() As Object ) As Object
If MethodName = "messageArrived" Then
Log("Message Arrived!")
Return Null
else If MethodName = "deliveryComplete" Then
Log("Delivery Complete!")
Return Null
else If MethodName = "connectionLost" Then
Log("Connection lost!")
Return Null
End If
End Sub
'Return true to allow the default exceptions handler to handle the uncaught exception.
Sub Application_Error (Error As Exception, StackTrace As String) As Boolean
Return True
End Sub
#If JAVA
//import java.lang.reflect.InvocationTargetException;
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.*;
//import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import org.bouncycastle.openssl.jcajce.JcePEMDecryptorProviderBuilder;
public class SslUtil
{
public SSLSocketFactory getSocketFactory (final String caCrtFile, final String crtFile, final String keyFile,
final String password) throws Exception
{
Security.addProvider(new BouncyCastleProvider());
// load CA certificate
PEMParser reader = new PEMParser(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))));
reader.readObject(); // skip the curve definition
X509Certificate caCert = (X509Certificate)reader.readObject();
reader.close();
// load client certificate
// reader = new PEMReader(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile)))));
reader = new PEMParser(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile)))));
X509Certificate cert = (X509Certificate)reader.readObject();
reader.close();
// load client private key
reader = new PEMParser(new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile)))));
Object object = (KeyPair)reader.readObject();
PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(password.toCharArray());
JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
KeyPair key;
if (object instanceof PEMEncryptedKeyPair)
{
System.out.println("Encrypted key - we will use provided password");
key = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
}
else
{
System.out.println("Unencrypted key - no password needed");
key = converter.getKeyPair((PEMKeyPair) object);
}
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();
}
}
#End If