hxb
2022-09-08 2a01ef5e49422cca49bc7476fc1b8be8c8556561
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
package com.hdl.sdk.link.core.utils;
 
import com.hdl.sdk.link.common.config.TopicConstant;
import com.hdl.sdk.link.common.utils.ByteUtils;
 
import com.hdl.sdk.link.core.bean.LinkRequest;
import com.hdl.sdk.link.core.config.HDLLinkConfig;
 
/**
 * Created by hxb on 2021/12/23.
 */
public class EncryptUtil {
    /**
     * 获取加密数据
     *
     * @param linkRequest 请求数据
     * @return
     */
    public static byte[] getEncryBytes(LinkRequest linkRequest) {
        try {
            //判断是否需要加密
 
            if (ifNeedEncrypt(linkRequest.getTopic(), linkRequest.isEncrypt())) {
                //需要加密
                byte[] dataBytes = AesUtil.aesEncrypt(linkRequest.getData(), HDLLinkConfig.getInstance().getLocalSecret());
                String headString = "Topic:" + linkRequest.getTopic() + "\r\n" + "Length:" + dataBytes.length + "\r\n" + "\r\n";
                byte[] headBytes = headString.getBytes("utf-8");
                byte[] sendBytes = ByteUtils.concatBytes(headBytes, dataBytes);
                return sendBytes;
            } else {
                return linkRequest.getSendBytes();
            }
 
        } catch (Exception e) {
            return new byte[]{};
        }
    }
 
    /**
     * 判断当前主题数据是否需要加密
     *
     * @param topicStr 当前主题
     * @return
     */
    public static boolean ifNeedEncrypt(String topicStr, boolean isLocalEncrypt) {
        //过滤相关需要加密的主题
        return (!topicStr.contains(TopicConstant.GATEWAY_AUTH_BROADCAST) //网关广播入网指令
                && !topicStr.contains(TopicConstant.DEIVCE_AUTH_REQUEST) //入网认证
                && !topicStr.contains(TopicConstant.GATEWAY_SEARCH) //搜索网关主题
                && !topicStr.contains(TopicConstant.GATEWAY_SEARCH_REPLY) //搜索网关主题回复
                && !topicStr.equals(TopicConstant.BROADCAST)
                && isLocalEncrypt//启用加密标志
        );
    }
}