MQTT serves as the push message pushing protocol for Android clients. The Android client needs to connect to the MQTT Proxy server via SSL/TLS for encrypted transmission of messages. Implementing this process requires two support, one for the MQTT protocol client and the other for the MQTT proxy server. There are many open-source Mqtt proxy servers, and I choose to use Mosquitto Broker.
Mosquitto install to Windows, I use Windows as the Mosquitto Proxy server
2. Installing OpenSSL
3. Generate a server certificate
OpenSSL req-new-x509-days 3650-keyout m2mqtt_ca.key-out m2mqtt_ca.crt
OpenSSL genrsa-des3-out M2mqtt_srv.key 1024
OpenSSL req-out M2mqtt_srv.csr-key m2mqtt_srv.key-new
OpenSSL x509-req-in m2mqtt_srv.csr-ca m2mqtt_ca.crt-cakey m2mqtt_ca.key-cacreateserial-out m2mqtt_srv.crt-days 3650
Android only supports BKS format certificates, using Keytool to replace the CRT as the BKS format,
4. Generate BKS Format certificate
Download Bcprov-jdk16-141.jar and put it in the 1.6.0.jdk/contents/home/lib/ext directory first.
Keytool-importcert-keystore test.bks-file M2mqtt_ca.crt-storetype Bks-provider Org.bouncycastle.jce.provider.BouncyCastleProvider
5. Configure Server-side
Modify Mosquitto_m2mqtt.conf
bind_address : Server name (in my case bind_address ppatierno-pc);
Port : MQTT port for SSL/TLS is 8883 (Port 8883);
cafile : path for CA certificate (cafile C:\OPENSSL-WIN64\BIN\PEM\M2MQTT_CA.CRT);
certfile : path for server certificate (CertFile C:\OPENSSL-WIN64\BIN\PEM\M2MQTT_SRV.CRT);
keyfile : Path Server private key (KeyFile C:\OpenSSL-Win64\bin\PEM\m2mqtt_srv.key);
tls_version : TLS version (Tls_version TLSV1);
Start the server
Mosquitto–c Mosquitto_m2mqtt.conf–v
6.android client, add Trust certificate code
Sslcontext context;
KeyStore ts = keystore.getinstance ("BKS");
Ts.load (Getresources (). Openrawresource (R.raw.test),
"123456". ToCharArray ());
Trustmanagerfactory TMF = trustmanagerfactory
. getinstance ("X509");
Tmf.init (TS);
Trustmanager[] tm = Tmf.gettrustmanagers ();
Context = Sslcontext.getinstance ("TLS");
Context.init (NULL, TM, NULL);
Socketfactory factory= Sslsocketfactory.getdefault ();
Socket socket =factory.createsocket ("localhost", 10000);
Socketfactory factory = Context.getsocketfactory ();
Conopt.setsocketfactory (Factory);
7. SOURCE Download Address
git clone https://github.com/widercode/AndroidMqttWithSSLSample.git