Dynamic registration for unique-certificate-per-product via HTTPS
This topic provides a Java code example that shows how a device using the unique-certificate-per-product method can perform dynamic registration over HTTPS to obtain a DeviceSecret for IoT Platform authentication.
Prerequisites
You have completed the following steps described in the unique-certificate-per-product documentation:
-
Create a product.
-
Enable dynamic registration.
-
(With pre-registration only) Add a device.
-
Flash device information on the production line.
Background information
IoT Platform supports multiple device authentication methods. For more information, see Device authentication.
IoT Platform supports unique-certificate-per-product pre-registration over HTTPS. For more information about the related topics and parameters, see Dynamic registration for a directly connected device over HTTPS.
Prepare the development environment
Development environment:
-
Operating system: Windows 10
-
JDK: JDK 8
Procedure
- Open IntelliJ IDEA and create a Maven project. For this example, name the project HTTPS Dynamic Registration.
- In your project's pom.xml file, add the Maven dependency and then click the Load Maven Changes icon to download the dependency packages.
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.83</version> </dependency> - In the /src/main/java directory of the HTTPS Dynamic Registration project, create a Java class. For this example, name the class DynamicRegisterByHttps.java and add the following code.Note
- If a
deviceis not activated, you can performdynamic registrationmultiple times. TheDeviceSecretfrom the most recent registration takes effect. Ensure that the latestDeviceSecretis persisted to thedevice. - If a
deviceis already activated, you must call the ResetThing API operation to reset itsdynamic registrationstatus to unregistered in the cloud before you can re-register thedevice.
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Random; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.net.ssl.HttpsURLConnection; import com.alibaba.fastjson.JSONObject; /** * Performs dynamic registration for a device. */ public class DynamicRegisterByHttps { // The region ID. Specify the ID of the region where your product is located. private static String regionId = "cn-shanghai"; // The encryption algorithm. Supported MAC algorithms: HmacMD5, HmacSHA1, and HmacSHA256. This must be the same as the value of the signMethod parameter. private static final String HMAC_ALGORITHM = "hmacsha1"; /** * Performs dynamic registration. * * @param productKey The ProductKey of the product. * @param productSecret The ProductSecret of the product. * @param deviceName The name of the device. * @throws Exception */ public void register(String productKey, String productSecret, String deviceName) throws Exception { // The request URL. URL url = new URL("https://iot-auth." + regionId + ".aliyuncs.com/auth/register/device"); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); conn.setDoOutput(true); conn.setDoInput(true); // Get the URLConnection object's output stream. PrintWriter out = new PrintWriter(conn.getOutputStream()); // Send the request parameters. out.print(registeredBody(productKey, productSecret, deviceName)); // Flush the output stream's buffer. out.flush(); // Get the URLConnection object's input stream. BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); // Read the response from the URL. String result = ""; String line = ""; while ((line = in.readLine()) != null) { result += line; } System.out.println("----- register result -----"); System.out.println(result); // Close the input and output streams. in.close(); out.close(); conn.disconnect(); } /** * Generates the request body for dynamic registration. * * @param productKey The ProductKey of the product. * @param productSecret The ProductSecret of the product. * @param deviceName The name of the device. * @return The dynamic registration payload. */ private String registeredBody(String productKey, String productSecret, String deviceName) { // Get a random number. Random r = new Random(); int random = r.nextInt(1000000); // The parameters for dynamic registration. JSONObject params = new JSONObject(); params.put("productKey", productKey); params.put("deviceName", deviceName); params.put("random", random); params.put("signMethod", HMAC_ALGORITHM); params.put("sign", sign(params, productSecret)); // Concatenate the payload. StringBuffer payload = new StringBuffer(); for (String key : params.keySet()) { payload.append(key); payload.append("="); payload.append(params.getString(key)); payload.append("&"); } payload.deleteCharAt(payload.length() - 1); System.out.println("----- register payload -----"); System.out.println(payload); return payload.toString(); } /** * Generates a signature for dynamic registration. * * @param params The parameters for the signature. * @param productSecret The ProductSecret of the product. * @return The signature as a hexadecimal string. */ private String sign(JSONObject params, String productSecret) { // Sort the request parameters in alphabetical order. Set<String> keys = getSortedKeys(params); // Exclude the 'sign' and 'signMethod' parameters. keys.remove("sign"); keys.remove("signMethod"); // Construct the plaintext for the signature. StringBuffer content = new StringBuffer(); for (String key : keys) { content.append(key); content.append(params.getString(key)); } // Calculate the signature. String sign = encrypt(content.toString(), productSecret); System.out.println("sign content=" + content); System.out.println("sign result=" + sign); return sign; } /** * Gets a sorted set of keys from a JSON object. * * @param json The JSON object to sort. * @return A sorted set of keys. */ private Set<String> getSortedKeys(JSONObject json) { SortedMap<String, String> map = new TreeMap<String, String>(); for (String key : json.keySet()) { String value = json.getString(key); map.put(key, value); } return map.keySet(); } /** * Encrypts content by using the HMAC_ALGORITHM. * * @param content The plaintext to encrypt. * @param secret The secret key. * @return The ciphertext. */ private String encrypt(String content, String secret) { try { byte[] text = content.getBytes(StandardCharsets.UTF_8); byte[] key = secret.getBytes(StandardCharsets.UTF_8); SecretKeySpec secretKey = new SecretKeySpec(key, HMAC_ALGORITHM); Mac mac = Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); return byte2hex(mac.doFinal(text)); } catch (Exception e) { e.printStackTrace(); return null; } } /** * Converts a byte array to a hexadecimal string. * * @param b The byte array. * @return The hexadecimal string. */ private String byte2hex(byte[] b) { StringBuffer sb = new StringBuffer(); for (int n = 0; b != null && n < b.length; n++) { String stmp = Integer.toHexString(b[n] & 0XFF); if (stmp.length() == 1) { sb.append('0'); } sb.append(stmp); } return sb.toString().toUpperCase(); } public static void main(String[] args) throws Exception { String productKey = "a1IoK******"; String productSecret = "6vEu5Qlj5S******"; String deviceName = "OvenDevice01"; // Perform dynamic registration. DynamicRegisterByHttps client = new DynamicRegisterByHttps(); client.register(productKey, productSecret, deviceName); // After dynamic registration succeeds, persist the DeviceSecret. } } - If a
- In the code, configure the following parameters with your actual device information.
Parameter Example Description regionId cn-shanghai The ID of the region where your IoT Platform service is deployed. For more information about region IDs, see Regions and zones. productKey a1IoK****** The ProductKey of the product, which is burned to the device. You can find the ProductKey on the Product Details page in the IoT Platform console. productSecret 6vEu5Qlj5S****** The ProductSecret of the product, which is burned to the device. You can find the ProductSecret on the Product Details page in the IoT Platform console. deviceName OvenDevice01 The name of your device. IoT Platform verifies the DeviceName during device activation. We recommend using a unique identifier that can be read directly from the device, such as its MAC address, IMEI, or serial number (SN), as the DeviceName.
- Run the DynamicRegisterByHttps.java file. The device sends an authentication request to IoT Platform that contains the DeviceName, ProductKey, and ProductSecret. After validating the request, IoT Platform returns a DeviceSecret (
6b14088fa377e8f852d82f7f********) to the device. The following sample output shows a successful registration.sign content=deviceNameOvenDevice01productKeya1xxx random52xxx sign result=95DBEEE0830D57594511501036F732xxx ----- register payload ----- random=52xxx &sign=95DBEEE0830D57594511501036xxx &productKey=a1xxx &deviceName=OvenDevice01&signMethod=hmacsha1 ----- register result ----- {"code":200,"data":{"deviceName":"OvenDevice01","deviceSecret":"6b14088fa377e8f852d82f7fxxx","productKey":"a1xxx"},"message":"success"} Process finished with exit code 0
Next steps
After the device obtains the device certificate (ProductKey, DeviceName, and DeviceSecret) required to connect to the cloud, use an MQTT client to connect the device to IoT Platform for data communication.
For more information, see Paho MQTT Java connection example.