2026-06-24 f4bd1f3c89d906131495a0aca5aaf82966378510
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package cn.iocoder.yudao.module.iot.core.util;
 
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.crypto.digest.HmacAlgorithm;
import cn.iocoder.yudao.module.iot.core.biz.dto.IotDeviceAuthReqDTO;
import cn.iocoder.yudao.module.iot.core.topic.IotDeviceIdentity;
 
/**
 * IoT 设备【认证】的工具类,参考阿里云
 *
 * @see <a href="https://help.aliyun.com/zh/iot/user-guide/how-do-i-obtain-mqtt-parameters-for-authentication">如何计算 MQTT 签名参数</a>
 */
public class IotDeviceAuthUtils {
 
    public static IotDeviceAuthReqDTO getAuthInfo(String productKey, String deviceName, String deviceSecret) {
        String clientId = buildClientId(productKey, deviceName);
        String username = buildUsername(productKey, deviceName);
        String password = buildPassword(deviceSecret,
                buildContent(clientId, productKey, deviceName, deviceSecret));
        return new IotDeviceAuthReqDTO(clientId, username, password);
    }
 
    public static String buildClientId(String productKey, String deviceName) {
        return String.format("%s.%s", productKey, deviceName);
    }
 
    public static String buildClientIdFromUsername(String username) {
        IotDeviceIdentity identity = parseUsername(username);
        if (identity == null) {
            return null;
        }
        return buildClientId(identity.getProductKey(), identity.getDeviceName());
    }
 
    public static String buildUsername(String productKey, String deviceName) {
        return String.format("%s&%s", deviceName, productKey);
    }
 
    public static String buildPassword(String deviceSecret, String content) {
        return DigestUtil.hmac(HmacAlgorithm.HmacSHA256, StrUtil.utf8Bytes(deviceSecret))
                .digestHex(content);
    }
 
    private static String buildContent(String clientId, String productKey, String deviceName, String deviceSecret) {
        return "clientId" + clientId +
                "deviceName" + deviceName +
                "deviceSecret" + deviceSecret +
                "productKey" + productKey;
    }
 
    public static IotDeviceIdentity parseUsername(String username) {
        String[] usernameParts = username.split("&");
        if (usernameParts.length != 2) {
            return null;
        }
        return new IotDeviceIdentity(usernameParts[1], usernameParts[0]);
    }
 
}