Android MQTT TLS/SSL 認證

MQTT 是一種輕量級的、靈活的物聯網消息交換和數據傳遞協議,致力於爲 IoT 開發人員實現靈活性與硬件/網絡資源的平衡。爲了確保通信安全,一般使用 TLS/SSL 來進行通信加密。java

本文主要介紹如何經過 Android 與 MQTT 進行 TLS/SSL 單向認證和雙向認證。android

準備

本文使用 Eclipse Paho Android ServiceBouncyCastle,添加依賴git

dependencies {
    implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
    implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
    implementation 'org.bouncycastle:bcpkix-jdk15on:1.59'
}

如下是 Android 鏈接 TLS/SSL 的核心代碼部分github

MqttConnectOptions options = new MqttConnectOptions();
SSLSocketFactory sslSocketFactory = ...
options.setSocketFactory(sslSocketFactory);

重點在於如何獲取 SSLSocketFactory,下面對單向認證和雙向認證分別進行說明。安全

單向認證

單向認證是指服務端認證客戶端,如下是核心代碼網絡

public static SSLSocketFactory getSingleSocketFactory(InputStream caCrtFileInputStream) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        X509Certificate caCert = null;

        BufferedInputStream bis = new BufferedInputStream(caCrtFileInputStream);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        while (bis.available() > 0) {
            caCert = (X509Certificate) cf.generateCertificate(bis);
        }
        KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
        caKs.load(null, null);
        caKs.setCertificateEntry("cert-certificate", caCert);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(caKs);
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, tmf.getTrustManagers(), null);
        return sslContext.getSocketFactory();
    }

咱們把 ca.crt 放到 res/raw 下,而後調用eclipse

try {
     InputStream caCrtFileI = context.getResources().openRawResource(R.raw.ca);
     options.setSocketFactory(getSingleSocketFactory(caCrtFile));
} catch (Exception e) {
     e.printStackTrace();
}

雙向認證

雙向認證是指服務端和客戶端相互認證,如下是關鍵代碼ide

public static SSLSocketFactory getSocketFactory(InputStream caCrtFile, InputStream crtFile, InputStream keyFile,
                                                    String password) throws Exception {
        Security.addProvider(new BouncyCastleProvider());

        // load CA certificate
        X509Certificate caCert = null;

        BufferedInputStream bis = new BufferedInputStream(caCrtFile);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        while (bis.available() > 0) {
            caCert = (X509Certificate) cf.generateCertificate(bis);
        }

        // load client certificate
        bis = new BufferedInputStream(crtFile);
        X509Certificate cert = null;
        while (bis.available() > 0) {
            cert = (X509Certificate) cf.generateCertificate(bis);
        }

        // load client private cert
        PEMParser pemParser = new PEMParser(new InputStreamReader(keyFile));
        Object object = pemParser.readObject();
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");
        KeyPair key = converter.getKeyPair((PEMKeyPair) object);

        KeyStore caKs = KeyStore.getInstance(KeyStore.getDefaultType());
        caKs.load(null, null);
        caKs.setCertificateEntry("cert-certificate", caCert);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(caKs);

        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setCertificateEntry("certificate", cert);
        ks.setKeyEntry("private-cert", key.getPrivate(), password.toCharArray(),
                new java.security.cert.Certificate[]{cert});
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, password.toCharArray());

        SSLContext context = SSLContext.getInstance("TLSv1.2");
        context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        return context.getSocketFactory();
    }

咱們須要準備好服務端證書,客戶端證書和祕鑰放到 res/raw 下,而後調用,注意密碼設爲空字符串加密

try {
    InputStream caCrtFile = context.getResources().openRawResource(R.raw.ca);
    InputStream crtFile = context.getResources().openRawResource(R.raw.cert);
    InputStream keyFile = context.getResources().openRawResource(R.raw.key);
    options.setSocketFactory(getSocketFactory(caCrtFile, crtFile, keyFile, ""));
} catch (Exception e) {
    e.printStackTrace();
}

以上就是如何在 Android 上與 MQTT 進行 TLS/SSL 單向認證和雙向認證。code

版權聲明: 本文爲 EMQ 原創,轉載請註明出處。

原文連接:https://www.emqx.io/cn/blog/android-mqtt-ssl-tls-authentication

相關文章
相關標籤/搜索