Example: Device authentication with an X.509 certificate
This topic uses a Java code example to show how a device can use an X.509 certificate from IoT Platform to authenticate its connection to the platform over MQTT.
Limitations
-
X.509 certificate authentication for direct MQTT connections is supported only for legacy public instances in the China (Shanghai) region.
-
Enterprise Edition instances support X.509 certificate authentication over the cloud gateway protocol. For more information, see Connect by using the cloud gateway protocol.
Prepare the development environment
The following development environment is used in this example:
Operating system: Windows 10
JDK version: JDK 8
Integrated development environment (IDE): IntelliJ IDEA Community Edition
Step 1: Create a product and a device
-
Log on to the IoT Platform console.
-
In the upper-left corner of the console, select China (Shanghai) as the region. On the Instance overview page, click the public instance.
In the left-side navigation pane, choose , and click Create Product.
-
On the Create product tab, configure the parameters and click OK.
In this example, a product named X509_Product is created. For Authentication method, select X.509 certificate. Configure the parameters as follows. See Create a product for detailed parameter descriptions. Set Category to Custom Category, Node type to Direct-connected device, Networking method to Wi-Fi, Data format to ICA standard data format (Alink JSON), and Use private CA certificate to No.
-
After the product is created, in the Add device section, click Add to create a device. For more information, see Create a single device.
In this example, select X509_Product for Product and enter X509device for DeviceName.
After the device is created, you can view its X.509 certificate on the Device details page.
-
Next to X.509, click Download to download the certificate.
You must import these certificate files when developing the device client.
Step 2: Configure client dependencies
-
Open IntelliJ IDEA and create a Maven project. In this example, the project is named X509-demo.
-
In the project's pom.xml file, add the Maven dependencies and click the Load Maven Changes icon to download the packages.
<dependency> <groupId>org.eclipse.paho</groupId> <artifactId>org.eclipse.paho.client.mqttv3</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.83</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>1.13</version> </dependency>
Step 3: Import device certificate files
Import the following certificate files into the resource directory of the X509-demo Java Maven project.
-
Unzip the X.509 certificate package that you downloaded from the Device details page to obtain the ****.cer and ****.key files. Place these two files in the resource directory.
NoteThe private key that IoT Platform provides is in PKCS#1 format, but native Java code requires the PKCS#8 format. You can use the OpenSSL tool to perform the conversion by running the following command:
openssl pkcs8 -topk8 -in devicex509.key -nocrypt -out devicex509_pkcs8.key -
To connect your device to IoT Platform over TLS (securemode=2), you must use the IoT Platform root certificate.
Download the GlobalSign R1 root certificate and place the root certificate file in the resource directory.
NoteThis CA root certificate is valid until January 28, 2028, for connections on port 1883. This certificate cannot be used for server verification after it expires. Therefore, ensure all devices that use TLS encryption can update their CA root certificates.
Step 4: Write the code
-
In the /src/main/java directory of the X509-demo Java Maven project, create a Java class. In this example, the class is named X509Test.java.
-
In X509Test.java, add the following code.
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.security.KeyFactory; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; import java.security.spec.PKCS8EncodedKeySpec; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; import org.apache.commons.codec.binary.Base64; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import com.alibaba.fastjson.JSONObject; public class X509Test { /** Region ID. Currently, only China (Shanghai) supports X.509 authentication. */ private static String regionId = "cn-shanghai"; /** The path of the root certificate. */ private static String rootPath = ""; /** The path of the device certificate. */ private static String certPath = ""; /** The path of the private key of the device certificate. */ private static String privateKeyPath = ""; /** The password, which is fixed as an empty string. */ private static String privateKeyPassword = ""; /** The topic for receiving X.509 authentication responses. You do not need to create or subscribe to this topic. You can use it directly. */ private static final String AUTH_TOPIC = "/ext/auth/identity/response"; /** Device productKey. Used to receive the productKey from IoT Platform. You do not need to set this parameter. */ private static String productKey = ""; /** Device deviceName. Used to receive the deviceName from IoT Platform. You do not need to set this parameter. */ private static String deviceName = ""; /** The MQTT client. */ private MqttClient sampleClient = null; /** * Establishes an MQTT connection. */ public void connect() { /** The connection endpoint. */ String broker = "ssl://x509.itls." + regionId + ".aliyuncs.com:1883"; /** The client ID. We recommend that you use the MAC address or serial number (SN) of the device. The ID must be 64 characters or less. */ String clientId = "."; /** Only securemode=2 is supported, which indicates that TLS is used. */ String clientOpts = "|securemode=2|"; /** The client ID for the MQTT connection. */ String mqttClientId = clientId + clientOpts; /** Establishes an MQTT connection. Because X.509 certificate authentication is used, a username and password are not required. */ connect(broker, mqttClientId, "", ""); } /** * Establishes an MQTT connection. * * @param serverURL The endpoint of the server to connect to. * @param clientId The client ID for the MQTT connection. * @param username The username for the MQTT connection. * @param password The password for the MQTT connection. */ protected void connect(String serverURL, String clientId, String username, String password) { try { MemoryPersistence persistence = new MemoryPersistence(); sampleClient = new MqttClient(serverURL, clientId, persistence); MqttConnectOptions connOpts = new MqttConnectOptions(); // MQTT 3.1.1 connOpts.setMqttVersion(4); // The username. connOpts.setUserName(username); // The password. connOpts.setPassword(password.toCharArray()); // To use TLS, download the root certificate (root.crt) and set securemode=2. connOpts.setSocketFactory(createSSLSocket()); // Do not clear offline messages. QoS 1 messages are stored in the cloud while the device is offline. connOpts.setCleanSession(false); // This demo disables automatic reconnection. We strongly recommend that you enable automatic reconnection in a production environment. connOpts.setAutomaticReconnect(false); // Set the keep-alive interval. We recommend a value of 300 seconds. connOpts.setKeepAliveInterval(300); // Set the callback first. If you connect before setting the callback, messages may be lost if they arrive before the callback is ready. sampleClient.setCallback(new MqttCallback() { @Override public void messageArrived(String topic, MqttMessage message) throws Exception { // Process only the X.509 authentication response. if (AUTH_TOPIC.equals(topic)) { JSONObject json = JSONObject .parseObject(new String(message.getPayload(), StandardCharsets.UTF_8)); productKey = json.getString("productKey"); deviceName = json.getString("deviceName"); } else { // Process other downstream messages. We strongly recommend that you process them in a separate thread to avoid blocking the callback. } } @Override public void deliveryComplete(IMqttDeliveryToken token) { } @Override public void connectionLost(Throwable cause) { } }); System.out.println("Connecting to broker: " + serverURL); sampleClient.connect(connOpts); System.out.print("Connected: clientId=" + clientId); System.out.println(",username=" + username + ",password=" + password); } catch (MqttException e) { System.out.print("connect failed: clientId=" + clientId); System.out.println(",username=" + username + ",password=" + password); System.out.println("reason " + e.getReasonCode()); System.out.println("msg " + e.getMessage()); System.out.println("loc " + e.getLocalizedMessage()); System.out.println("cause " + e.getCause()); System.out.println("except " + e); e.printStackTrace(); } catch (Exception e) { System.out.print("connect exception: clientId=" + clientId); System.out.println(",username=" + username + ",password=" + password); System.out.println("msg " + e.getMessage()); e.printStackTrace(); } } /** * Publishes a message with the default QoS level of 0. * * @param topic The topic to which the message is published. * @param payload The content of the message. */ public void publish(String topic, String payload) { byte[] content = payload.getBytes(StandardCharsets.UTF_8); publish(topic, 0, content); } /** * Publishes a message. * * @param topic The topic to which the message is published. * @param qos The Quality of Service (QoS) level. The platform supports QoS 0 and QoS 1, but not QoS 2. * @param payload The content of the message. */ public void publish(String topic, int qos, byte[] payload) { MqttMessage message = new MqttMessage(payload); message.setQos(qos); try { sampleClient.publish(topic, message); System.out.println("Message published: topic=" + topic + ",qos=" + qos); } catch (MqttException e) { System.out.println("publish failed: topic=" + topic + ",qos=" + qos); System.out.println("reason " + e.getReasonCode()); System.out.println("msg " + e.getMessage()); System.out.println("loc " + e.getLocalizedMessage()); System.out.println("cause " + e.getCause()); System.out.println("except " + e); e.printStackTrace(); } } protected SSLSocketFactory createSSLSocket() throws Exception { /** The IoT Platform root certificate. You can download it from the official documentation at https://www.alibabacloud.com/help/en/iot-platform/latest/root-certificates. */ /** The X.509 device certificate. You can download it from the device details page in the IoT Platform console. */ /** The CA certificate is used to authenticate the server. */ InputStream in = new FileInputStream(new File(rootPath)); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate ca = cf.generateCertificate(in); in.close(); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(keyStore); /** The client key and certificates are sent to the server for authentication. */ FileInputStream certIn = new FileInputStream(new File(certPath)); CertificateFactory certCf = CertificateFactory.getInstance("X.509"); Certificate certCa = certCf.generateCertificate(certIn); certIn.close(); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setCertificateEntry("certificate", certCa); PrivateKey privateKey = getPrivateKey(privateKeyPath); ks.setKeyEntry("private-key", privateKey, privateKeyPassword.toCharArray(), new Certificate[] {certCa}); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, privateKeyPassword.toCharArray()); SSLContext context = SSLContext.getInstance("TLSV1.2"); context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); SSLSocketFactory socketFactory = context.getSocketFactory(); return socketFactory; } private PrivateKey getPrivateKey(String path) throws Exception { byte[] buffer = Base64.decodeBase64(getPem(path)); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(keySpec); } private String getPem(String path) throws Exception { InputStream in = new FileInputStream(new File(path)); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String readLine = null; StringBuilder sb = new StringBuilder(); while ((readLine = br.readLine()) != null) { if (readLine.charAt(0) == '-') { continue; } else { sb.append(readLine); sb.append('\r'); } } in.close(); return sb.toString(); } /** * After the connection is established, IoT Platform sends the productKey and deviceName to the /ext/auth/identity/response topic. * You can use this information to construct topics for publishing messages and subscribing to topics. * * @param args */ public static void main(String[] args) { X509Test client = new X509Test(); /** Set the paths for the device certificate files. */ client.connect(); /** After a successful connection, sleep for 2 seconds to ensure that the productKey and deviceName are received from the cloud. Otherwise, the productKey and deviceName fields in the message topics might be empty. */ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } /** Send a message to verify that the connection is successful. */ String updateTopic = "/" + productKey + "/" + deviceName + "/user/update"; client.publish(updateTopic, "hello mqtt with X.509 auth"); } } -
In the preceding code, configure the paths to the device certificate and its private key.
In this example, the certificate files in the resource directory of the X509-demo project are
root.crt,x509device.cer, anddevicex509_pkcs8.key. Set the paths to the corresponding certificate files.// The path of the root certificate. private static String rootPath = "***/resource/root.crt"; // The path of the device certificate. private static String certPath = "***/resource/x509device.cer"; // The path of the private key of the device certificate. private static String privateKeyPath = "***/resource/devicex509_pkcs8.key";
Step 5: Run the program
Run the X509Test.java main method.
The following logs indicate a successful run:
Connecting to broker: ssl://x509.itls.cn-shanghai.aliyuncs.com:1883
Connected: clientId=.|securemode=2|,username=,password=
Message published: topic=/a1****m/X509device/user/update,qos=0
Log on to the IoT Platform console to view the device status and logs for the public instance.
-
Choose . The device status is displayed as Online.
-
Choose to view the logs. On the Cloud run logs tab, you can view records for Device-to-cloud messages and Device behavior. Click View for a log entry to see the message details and confirm that the message content matches the content sent from the code.